用cv2.line()函数在一张道路交通图中画出一个不规则图形,写一段代码计算不规则图形的像素和整幅图像的像素比
时间: 2024-05-19 11:16:14 浏览: 71
根据图片 获得不规则图形
import cv2
# 读取道路交通图
img = cv2.imread('road_traffic.jpg')
# 画出不规则图形
cv2.line(img, (100, 100), (200, 200), (0, 0, 255), 5)
cv2.line(img, (200, 200), (300, 100), (0, 0, 255), 5)
cv2.line(img, (300, 100), (100, 100), (0, 0, 255), 5)
cv2.line(img, (150, 150), (250, 150), (0, 0, 255), 5)
# 计算不规则图形的像素和
roi = img[100:201, 100:301]
roi_gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
ret, roi_thresh = cv2.threshold(roi_gray, 1, 255, cv2.THRESH_BINARY)
roi_pixel_num = cv2.countNonZero(roi_thresh)
# 计算整幅图像的像素和
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, img_thresh = cv2.threshold(img_gray, 1, 255, cv2.THRESH_BINARY)
img_pixel_num = cv2.countNonZero(img_thresh)
# 计算像素比
pixel_ratio = roi_pixel_num / img_pixel_num
# 显示图像和像素比
cv2.imshow('image', img)
print('不规则图形的像素和:', roi_pixel_num)
print('整幅图像的像素和:', img_pixel_num)
print('不规则图形的像素和与整幅图像的像素比:', pixel_ratio)
cv2.waitKey(0)
cv2.destroyAllWindows()
阅读全文