我需要计算如下图所示的非对称形状的面积
此代码读取图像并将其转换为灰色并找到形状 我需要找出不对称形状的区域
import numpy as np
import cv2
# load the image, convert it to grayscale, and blur it slightly
image = cv2.imread("download.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
# find contours in the edge map
cnts = cv2.findContours(gray.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image,cnts, 0, (255, 0, 0), 8)
cv2.imshow("Image", image)
cv2.waitKey(0)
答案 0 :(得分:2)
我已经测试了您的代码,发现没有找到形状的轮廓。这是因为您以灰色图像制作了cv2.findContours
。该图像应为二进制图像,因此我使用了cv2.threshold
。然后可以使用cv2.contourArea
计算面积。
下面是代码和结果。
import numpy as np
import cv2
image = cv2.imread("1.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
_,thresh = cv2.threshold(gray,128,255,cv2.THRESH_BINARY_INV)
im, cnts, hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for cnt in cnts:
cv2.drawContours(image,cnts, -1, (0, 0, 255), 1)
print(cv2.contourArea(cnt))
cv2.imshow("thresh", thresh)
cv2.imshow("Image", image)
cv2.waitKey(0)
>> 8656.0
>> 3824.5