import cv2
import numpy as np
img = cv2.imread('img.jpg')
height = img.shape[0]
width = img.shape[1]
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)
cv2.imshow("Mask", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
ave = cv2.mean(thresh)[0]/255
print(ave)
0.310184375
area = ave*height*width
print(area)
198518.0
import cv2
import numpy as np
img = cv2.imread('img.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)
cv2.imshow("Mask", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
area2 = cv2.countNonZero(thresh)
print(area2)
198518
附加2
如果您知道以米为单位的地面面积或尺寸(根据您的评论,0.8米在一侧),对应于图像覆盖的面积,则与非零像素计数相对应的地面面积将是:
area on ground for nonzero pixels = count * 0.8 * 0.8 / (width * height)
其中width和height是图像的像素尺寸。
import cv2
import numpy as np
img = cv2.imread('img.jpg')
height = img.shape[0]
width = img.shape[1]
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)
cv2.imshow("Mask", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
count = cv2.countNonZero(thresh)
area = count*0.8*0.8/(width*height)
print(area)
0.19851800000000003
area = count * 0.8 * 0.8 / (width * height)
。 - fmw42(0[黑色] - 255[白色])
cv2.threshold
来获取大于60
的像素(3,3)
和cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
填充小的白色斑点代码
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('RIUXF.jpg',0)
hist = cv2.calcHist([img],[0],None,[256],[0,256])
# Area occupied by black region
black_area = np.true_divide(hist[0],np.prod(img.shape))[0]*100
# extract no black parts
thresh = cv2.threshold(img,60,255,cv2.THRESH_BINARY)[1]
kernel = np.ones((3,3),np.uint8)
# fill in the small white spots
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
# extract the contours
contours = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
blank_image = np.zeros((img.shape),np.uint8)
image_area = np.prod(img.shape)
# iterate through the contours detected from right top corner
for i,c in enumerate(contours[::-1]):
# turn blank_image black
blank_image *= 0
# draw filled contour
cv2.drawContours(blank_image, [c], 0, (255), thickness=cv2.FILLED)
contour_area = cv2.contourArea(c)
# percentage of area contour
contour_area_pc = np.true_divide(int(contour_area),image_area)*100 if int(contour_area) > 1 else 0
text = ' '.join(['Contour:',str(i),'Area:',str(round(contour_area,2)),'Percentage Area:',str(round(contour_area_pc,2))])
cv2.putText(blank_image,text,(10,60), cv2.FONT_HERSHEY_SIMPLEX, 1,(255),2,cv2.LINE_AA)
plt.imshow(blank_image, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
样例输出
PS:我怀疑cv2计算的面积是否正确