一张图片中有使用cv2.line()画的不规则图像,写一段代码,计算该不规则图形中的像素点个数和总的像素点个数之比,Python语言
时间: 2024-05-30 10:14:03 浏览: 84
python cv2截取不规则区域图片实例
import cv2
# 读取图像
img = cv2.imread("irregular_shape.jpg")
# 将图像转为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 使用cv2.findContours()函数提取轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
# 统计像素点个数
total_pixels = img.shape[0] * img.shape[1]
irregular_pixels = cv2.countNonZero(thresh)
# 计算比值
ratio = irregular_pixels / total_pixels
# 显示结果
cv2.imshow("image", img)
print("不规则图形像素点个数:", irregular_pixels)
print("总像素点个数:", total_pixels)
print("比值:", ratio)
cv2.waitKey(0)
cv2.destroyAllWindows()
阅读全文