写一段python代码将图像中所有缺陷边缘进行用矩形框起来
时间: 2023-03-13 19:06:09 浏览: 113
python实现在图片上画特定大小角度矩形框
5星 · 资源好评率100%
# 导入所需的模块
import cv2
import numpy as np # 读取图像
img = cv2.imread('image.jpg') # 转换为灰度图像
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # 检测边缘
edges = cv2.Canny(gray,50,150,apertureSize = 3) # 检测缺陷边缘
lines = cv2.HoughLines(edges,1,np.pi/180,200) # 遍历检测到的缺陷边缘
for line in lines:
for rho,theta in line:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
# 用矩形框起来
cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2) # 显示结果
cv2.imshow('Result Image',img)
cv2.waitKey(0)
阅读全文