Python for循环仅保存区域的最后一个值?

时间:2020-06-03 06:34:41

标签: python-3.x pandas matplotlib

I使用吹线代码进行轮廓检测及其相应的面积计算,并在打印区域时打印所有值,但仅保存最后保存在CSV文件中的值

import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import os
import pandas as pd


img = cv2.imread('C:\pfm\segmented/L501.jpg')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


from scipy import ndimage as nd
gaussian_img = nd.gaussian_filter(image, sigma=3)

ret, thresh = cv2.threshold(gaussian_img, 127,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

#print ('No of shapes:', format(len(contours)))


for cnt in contours:

    M= cv2.moments(cnt)
        #print(M)

    if M["m00"] != 0:

        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
    else:
        cx, cy = 0,0

    center = (cx,cy)


    cv2.drawContours(img, contours, -1, (0,255,0),2)


    plt.imshow(img)
    plt.imsave("C:\pfm\dataframe_csv\L501.jpg", img)

    area = cv2.contourArea(cnt)

    print(area)

    df = pd.DataFrame()
    df['Area'] = area
    df.to_csv("C:\pfm\dataframe_csv\L501.csv")

1 个答案:

答案 0 :(得分:0)

在代码中,在每个循环中都重置df数据帧。
尝试以下代码:

import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import os
import pandas as pd


img = cv2.imread('C:\pfm\segmented/L501.jpg')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


from scipy import ndimage as nd
gaussian_img = nd.gaussian_filter(image, sigma=3)

ret, thresh = cv2.threshold(gaussian_img, 127,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

#print ('No of shapes:', format(len(contours)))

area_list = []
df = pd.DataFrame()

for cnt in contours:

    M= cv2.moments(cnt)
        #print(M)

    if M["m00"] != 0:

        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
    else:
        cx, cy = 0,0

    center = (cx,cy)


    cv2.drawContours(img, contours, -1, (0,255,0),2)


    plt.imshow(img)
    plt.imsave("C:\pfm\dataframe_csv\L501.jpg", img)

    area = cv2.contourArea(cnt)

    print(area)

    area_list.append(area)

df['Area'] = area_list
df.to_csv("C:\pfm\dataframe_csv\L501.csv")

我没有在每个循环中将area附加到df数据帧,而是将其附加到列表area_list中。请注意,我在for循环之前创建了这个空列表,以初始化它以及df数据帧。当所有循环结束后,我通过将先前生成的列表保存在数据帧的'Area'列中。这样df不会为空,并且代码效率更高。