利用sobel算子边缘检测,写一份代码,找到二值化图像中矩形的角坐标
时间: 2023-06-05 15:05:37 浏览: 134
好的,以下是代码:
```python
import cv2
# 读取图像并转化为灰度图
img = cv2.imread('yourimage.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 进行边缘检测
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
edges = cv2.bitwise_or(sobelx, sobely)
# 将边缘检测结果进行二值化处理
thresh = cv2.threshold(edges, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
# 进行形态学处理,填充边缘空隙
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# 寻找轮廓,并筛选出矩形
contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = box.astype(int)
cv2.drawContours(img, [box], 0, (0, 0, 255), 2) # 绘制矩形
# 显示结果
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请将“yourimage.jpg”替换成你想要检测的图像路径。这份代码会对图像进行Sobel算子边缘检测,并找到其中的矩形,然后在图像上绘制出矩形。
阅读全文