首页 > 解决方案 > 如何检测空间图案的边缘?

问题描述

我正在建造一台新机器,但边缘检测有问题。我在一个圆柱体上放了一张纸,如下图所示。如何检测这张纸的边缘?

在此处输入图像描述

我试图建立一个 LED 背景,但这篇论文非常大。因此,我的机器没有足够的空间来运行。

标签: opencvimage-processing

解决方案


您可以使用以下代码作为参考。在这里,我基本上是使用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)

输出:

在此处输入图像描述


推荐阅读