准备工作:python3.7, pycharm,opencv-python模块。(不懂的话,网上有许多资料可供查询)
全部代码如下(直接可运行,需将图片路径换成自己电脑的图片路径)
import cv2 as cv
import numpy as np
# canny边缘检测
def canny_demo(image):
t = 140
canny_output = cv.Canny(image, t, t * 2)
cv.imshow("canny_output", canny_output)
cv.imwrite("D:\\tupian\canny_output.png", canny_output)
return canny_output
# 读取图像
src1 = cv.imread("D:\\t0.bmp")
src2 = cv.imread("D:\\t0.bmp")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src1)
# 调用
binary = canny_demo(src2)
# 轮廓发现
contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
areas, arclens = [], []
for c in range(len(contours)):
# 面积
areas.append(cv.contourArea(contours[c]))
# 周长
arclens.append(cv.arcLength(contours[c], True))
area_id = areas.index(max(areas))
areamax = max(areas)
arclenmax = max(arclens)
# 矩形
rect = cv.minAreaRect(contours[area_id])
cx, cy = rect[0]
box = cv.boxPoints(rect)
box = np.int0(box)
# 轮廓描绘
cv.drawContours(src1,[box],0,(0,255,0),2)
cv.circle(src1, (np.int(cx), np.int(cy)), 2, (255, 0, 0), 2, 8, 0)
cv.drawContours(src1, contours, area_id, (0, 0, 255), 2, 8)
cv.putText(src2, "area:" + str(areamax), (50, 50), cv.FONT_HERSHEY_SIMPLEX, .7, (0, 0, 0), 1)
cv.putText(src2, "arclen:" + str(arclenmax), (50, 90), cv.FONT_HERSHEY_SIMPLEX, .7, (0, 0, 0), 1)
cv.putText(src2, "color:" + 'red' , (230,170), cv.FONT_HERSHEY_SCRIPT_SIMPLEX, .7, (0, 0, 0), 1)
# 图像显示
cv.imshow("contours_analysis", src1)
cv.imshow('', src2)
cv.imwrite("D:\\tipian\area.png", src1)
cv.waitKey(0)
# cv.destroyAllWindows()
原始图片:
代码处理后的图片:
更多功能和详细的注释请关注我的博客或者评论中留下方式