【问题标题】:Python for loop save only last value of area?Python for循环仅保存区域的最后一个值?
【发布时间】:2020-06-03 06:34:41
【问题描述】:

我使用代码行进行轮廓检测及其相应的面积计算,并在打印区域期间打印所有值,但在保存时只保存最后一个值保存在 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")

【问题讨论】:

  • 已回复here
  • 仅供参考:彻底回答问题非常耗时。如果您的问题已解决,请通过接受最适合您的需求的解决方案表示感谢。 位于答案左上角的 / 箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您的声望超过 15,您也可以使用 / 箭头对答案的有用性进行投票。 如果解决方案不能回答问题,请发表评论What should I do when someone answers my question?。谢谢

标签: python python-3.x pandas matplotlib


【解决方案1】:

在您的代码中,在每个循环中,您都会重置 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不为空,代码效率更高。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2022-01-25
    • 2015-06-02
    • 1970-01-01
    • 2019-09-20
    • 2017-07-28
    • 2019-05-15
    相关资源
    最近更新 更多