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")
答案 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
不会为空,并且代码效率更高。