opencv - 如何检测空间图案的边缘?
问题描述
我正在建造一台新机器,但边缘检测有问题。我在一个圆柱体上放了一张纸,如下图所示。如何检测这张纸的边缘?
我试图建立一个 LED 背景,但这篇论文非常大。因此,我的机器没有足够的空间来运行。
解决方案
您可以使用以下代码作为参考。在这里,我基本上是使用cv2.inRange
函数从图像中分割出浅绿色(不是深绿色,否则也会检测到其中一个轴的边缘),最后Canny
在分割图像的灰度版本上应用边缘检测,即cv2.Canny
.
import cv2
import numpy as np
img = cv2.imread('cylinder.png')
# convert to HSV color space
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Threshold the HSV image to get green colors by defining range of green color in HSV
mask = cv2.inRange(img_hsv, (36,0,0), (55,255,255))
# Bitwise-AND mask and original image
res = cv2.bitwise_and(img, img, mask = mask)
# coverting image with green colored region of interest from HSV to RGB
img_hsv2bgr = cv2.cvtColor(res, cv2.COLOR_HSV2BGR)
# coverting image from RGB to GRAYSCALE
img_gray = cv2.cvtColor(img_hsv2bgr, cv2.COLOR_BGR2GRAY)
# canny edge detection
edges = cv2.Canny(img_gray, 100, 200)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出:
编辑:在对上面的代码进行一些修改之后,比如分割黄色部分和浅绿色,并在传递给cv2.Canny
函数之前应用高斯模糊,可以提供比上面更好的输出。
代码:
# Threshold the HSV image to get both green and yellow colors by defining range of color in HSV
mask_green = cv2.inRange(img_hsv, (36,0,0), (55,255,255))
mask_yellow = cv2.inRange(img_hsv, (21, 39, 64), (38, 255, 255))
mask = cv2.bitwise_or(mask_green, mask_yellow)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(img, img, mask = mask)
# coverting image with green colored region of interest from HSV to RGB
frame_hsv2bgr = cv2.cvtColor(res, cv2.COLOR_HSV2BGR)
# coverting image from RGB to GRAYSCALE
frame_gray = cv2.cvtColor(frame_hsv2bgr, cv2.COLOR_BGR2GRAY)
gaussian_blurred = cv2.GaussianBlur(frame_gray,(5, 3), 0)
# canny edge detection
edges = cv2.Canny(gaussian_blurred, 100, 200)
输出:
推荐阅读
- sql - 遍历 SQL 选择查询以获取更多相关数据
- javascript - 是否可以调用具有 Python 依赖项的 JavaScript 函数?
- javascript - chartjs-plugin-streaming:onRefresh() 回调不起作用
- javascript - 打印预览通过缩放动态适应 HTML 页面内容
- flutter - 在 Flutter 中排序后如何刷新 ListView?
- javascript - 在父类组件中反应功能(钩子)组件
- python - 尝试使用 Discord.py 在 Raspberry Pi 3B+ 上运行音乐机器人,有时在 voice_client.connect() 或 voice_channel.connect() 期间它会冻结
- sql - Oracle 按范围分区
- raspberry-pi - 无法在树莓派 4b 上打开 /dev/mem
- java - WebClient ExchangeFilterFunction 缓存来自 ThreadLocal 的值