计算每个轮廓的弧长和面积,单位是像素
approxPolyDP
import cv2 as cv
import numpy as np
def measure_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
print("threshold value : %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)
mm = cv.moments(contour)
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("contour area %s" % area)
cv.imshow("measure-contours", image)
src = cv.imread("resource/num.png")
cv.namedWindow("Test", cv.WINDOW_AUTOSIZE)
cv.imshow("Test", src)
measure_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
import cv2 as cv
import numpy as np
def measure_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
print("threshold value : %s" % ret)
cv.imshow("binary image", binary)
dst = cv.cvtColor(binary, cv.COLOR_GRAY2BGR)
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("rectangle rate : %s" % rate)
mm = cv.moments(contour) # 计算几何矩
# 字典类型
print(type(mm))
# cx = mm['m10'] / mm['m00']
# cy = mm['m01'] / mm['m00']
# 3:点的半径;下一个参数:颜色; -1:填充
# cv.circle(dst, (np.int(cx), np.int(cy)), 3, (0, 255, 255), -1)
# cv.rectangle(dst, (x, y), (x + w, y + h), (0, 0, 255), 2)
print("contour area %s" % area)
approxCurve = cv.approxPolyDP(contour, 4, True)
print(approxCurve.shape)
# 大于6条小线段,是圆
if approxCurve.shape[0] > 6:
cv.drawContours(dst, contours, i, (0, 255, 0), 2)
# 矩形
if approxCurve.shape[0] == 4:
cv.drawContours(dst, contours, i, (0, 0, 255), 2)
cv.imshow("measure-contours", dst)
src = cv.imread("resource/lk.png")
cv.namedWindow("Test", cv.WINDOW_AUTOSIZE)
cv.imshow("Test", src)
measure_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()