在我的项目中,我需要计算小植物根系图像的面积。

我使用了以下两种密码,但我仍对此表示怀疑:
import cv2
image = cv2.imread('D:/R4-15.TIF')
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img_gray, 180, 255, cv2.THRESH_BINARY)
cv2.imshow('Binary', thresh)
contours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)
image_copy = image.copy()
cv2.drawContours(image=image_copy, contours=contours, contourIdx=-1, color=(0, 255, 0), thickness=-1, lineType=cv2.LINE_AA)
cv2.imshow('Contour_image', image_copy)
cv2.waitKey(0)
cv2.imwrite('contours_image1.jpg', image_copy)
cv2.destroyAllWindows()
cnt = contours[0]
area= cv2.contourArea(cnt)
print(area)
cv2.waitKey(0)
cv2.destroyAllWindows()import cv2
import numpy as np
img = cv2.imread('D:/R4-16.TIF')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,165,255,cv2.THRESH_BINARY)
cv2.imshow("Mask", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
area2 = cv2.countNonZero(thresh)
print(area2)发布于 2022-06-20 06:47:24
如果您的阈值图像没有噪音,那么countNonZero是好的。
但是,如果在阈值之后,你仍然有一些噪声,通常是分散在各处的小黑点,那么最好把它们过滤掉。
其中一种可能的方法是应用形态学打开,请参阅形态运算。但它也肯定地改变了地面真相的根源形象。
我建议使用connectedComponentsWithStats
把它和你被打掉的根部形象相提并论。
返回的值之一是stats,它也将保存每个连接组件的区域。然后你可以放下所有的小部件,这是一种噪音,并拾取一个或几个最大的黑色组件,并采取他们的面积。
有关维基中连接组件的更多信息
调用示例
# ...
# Put it at the end of you second snippet,
# where you get thresholded image
num_components, labels, stats, centroids = \
cv2.connectedComponentsWithStats(thresh)
# Here you can also use something like this:
# total_area = list(itertools.accumulate(
# stats, lambda t, x: t + x[cv2.CC_STAT_AREA])
# )[-1]
areas = stats[:, cv2.CC_STAT_AREA]
areas = list(sorted(areas))
assert \
len(areas) >= 2, \
"We expect at least two components: white area" \
" and at least one root fragment."
# We suppose that white area is the biggest one, thus
# we have to count everything except the last item in sorted
# list.
total_area = 0
noise_threshold = 5 # If area is less than 5 pixels we drop it
for i, area in enumerate(areas[:-1]):
print(f"Area of root part #{i} is: {area}")
if area > noise_threshold:
total_area += area
print(f"Total area is: {total_area}")https://stackoverflow.com/questions/72682621
复制相似问题