image.png image.png image.png弧长与面积
def measure_function(image):
dst = cv.GaussianBlur(image,(7,7),0)
gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
print("二值阈值:%s" % ret)
cv.imshow("Binary image", binary)
outImage, contours, hireachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
area = cv.contourArea(contour) # 面积
x, y, w, h = cv.boundingRect(contour) # 外接矩形
rate = min(w,h)/max(w,h)
print("宽高比:%s"%rate)
mm = cv.moments(contour) # 几何矩
print(type(mm))
cx = mm['m10']/mm['m00']
cy = mm['m01']/mm['m00']
cv.circle(image, (np.int(cx), np.int(cy)), 3, (0, 255, 255), -1)#中心
cv.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 2)
print("面积:%s"%area)
cv.imshow("measure-contours", image)
image.png
cv.approxPolyDP
def measure_function(image):
dst = cv.GaussianBlur(image, (7, 7), 0)
gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(
gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
print("二值阈值:%s" % ret)
cv.imshow("Binary image", binary)
outImage, contours, hireachy = cv.findContours(
binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
x, y, w, h = cv.boundingRect(contour) # 外接矩形
mm = cv.moments(contour) # 几何矩
print(type(mm))
cx = mm['m10']/mm['m00']
cy = mm['m01']/mm['m00']
cv.circle(image, (np.int(cx), np.int(cy)), 3, (0, 255, 255), -1) # 中心
'''
cv.approxPolyDP:
curve:contour
epsilon = 4 :越小越逼近真实形状
closed = True
'''
approxCurve = cv.approxPolyDP(contour, 4, closed=True)
print(approxCurve.shape)
if approxCurve.shape[0] > 6: # 边数大于6,近似圆形,椭圆
cv.drawContours(image, contours, i, (0, 255, 0), 2)
if approxCurve.shape[0] == 3: # 三角形
cv.drawContours(image, contours, i, (0, 0, 255), 2)
if approxCurve.shape[0] == 4: # 四角形
cv.drawContours(image, contours, i, (0, 255, 125), 2)
cv.imshow("measure-contours", image)
image.png
网友评论