我正在尝试提取这部分
来自此
我试图检测形状,没有办法,训练一束虹彩...(没有负数),....位置可以变化(并非全部插入)并且角度也不相同。我不能一一裁剪:-(
任何建议?在此先感谢
PS原始图像在这里https://pasteboard.co/JaTSoJF.png(对不起,> 2Mb)
在完成@ganeshtata之后,我们得到了
import cv2
import numpy as np
img = cv2.imread('cropsmall.png')
height, width = img.shape[:2]
green_channel = img[:,0:] # Blue channel extraction
res = cv2.fastNlMeansDenoising(green_channel, None, 3, 7, 21) # Non-local means denoising
cv2.imshow('denoised',res)
edges = cv2.Canny(res, 11, 11, 3) # Edge detection
kernel = np.ones((30, 30),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel) # Morphological closing
im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find all contours in the image
for cnt in contours: # Iterate through all contours
x, y, w, h = cv2.boundingRect(cnt) # Reject contours whose height is less than half the image height
if h < height / 2:
continue
y = 0 # Assuming that all shapes start from the top of the image
cv2.rectangle(img, (x, y), \
(x + w, y + h), (0, 255, 0), 2)
cv2.imshow('IMG',img)
cv2.imwrite("test.jpg",img)
cv2.waitKey(0)
给我们
不错...
我使用以下方法来提取问题中指定的模式。
读取图像并从图像中提取蓝色通道。
import cv2
import numpy as np
img = cv2.imread('image.png')
height, width = img.shape[:2]
blue_channel = img[:,:,0]
在蓝色通道图像上应用OpenCV的Non-local Means Denoising algorithm。这样可以确保图像中的大多数随机噪声都得到平滑处理。
res = cv2.fastNlMeansDenoising(blue_channel, None, 3, 7, 21)
应用Canny边缘检测。
edges = cv2.Canny(res, 1, 10, 3)
应用Morpological Closing尝试关闭图像中的小间隙/孔。
kernel = np.ones((30, 30),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
使用cv2.findContours查找图像中的所有轮廓。找到所有轮廓后,我们可以使用cv2.boundingRect确定每个轮廓的边界框。
im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find all contours
for cnt in contours: # Iterate through all contours
x, y, w, h = cv2.boundingRect(cnt) $ Get contour bounding box
if h < height / 2: # Reject contours whose height is less than half the image height
continue
y = 0 # Assuming that all shapes start from the top of the image
cv2.rectangle(img, (x, y), \
(x + w, y + h), (0, 255, 0), 2)
完整代码-
import cv2
import numpy as np
img = cv2.imread('image.png')
height, width = img.shape[:2]
blue_channel = img[:,:,0] # Blue channel extraction
res = cv2.fastNlMeansDenoising(blue_channel, None, 3, 7, 21) # Non-local means denoising
edges = cv2.Canny(res, 1, 10, 3) # Edge detection
kernel = np.ones((30, 30),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel) # Morphological closing
im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find all contours in the image
for cnt in contours: # Iterate through all contours
x, y, w, h = cv2.boundingRect(cnt) # Reject contours whose height is less than half the image height
if h < height / 2:
continue
y = 0 # Assuming that all shapes start from the top of the image
cv2.rectangle(img, (x, y), \
(x + w, y + h), (0, 255, 0), 2)
注意-此方法适用于您发布的示例图像。它可能/可能不会针对所有图像进行概括。