因此,我有以下由多个小块组成的图像,并且希望获得其外部轮廓,如下所示:
我以前曾经使用过轮廓逼近和凸壳函数来获得近似的外部轮廓,但是它们只是由1个单一轮廓组成,而在这种情况下,它们较小零件很重要。
我以前使用的功能与此相似:
canvas = np.zeros(img.shape, np.uint8)
img2gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
kernel = np.ones((5,5),np.float32)/25
img2gray = cv2.filter2D(img2gray,-1,kernel)
ret,thresh = cv2.threshold(img2gray,120,255,cv2.THRESH_BINARY_INV)
im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]
max_area = cv2.contourArea(cnt)
for cont in contours:
if cv2.contourArea(cont) > max_area:
cnt = cont
max_area = cv2.contourArea(cont)
hull = cv2.convexHull(cnt)
cv2.drawContours(canvas, hull, -1, (0, 255, 0), 3)
您可能会猜到,输出与期望的输出相差甚远:
关于如何使其更接近所需的任何想法?
答案 0 :(得分:0)
您可以应用形态学操作来闭合轮廓,也许可行
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
然后您执行膨胀操作以闭合具有小间隙的轮廓
thresh = cv2.dilate(thresh, kernel,iterations = 1)
请给我您的反馈意见。
答案 1 :(得分:0)
正如@Amine所说,形态学运算将是必经之路,尤其是扩张。可以找到更多信息here。举了一个小例子,您可以微调,但我认为它非常接近所需的输出。
import cv2
import numpy as np
cv_img = cv2.imread('spot.jpg', 0)
im_copy = cv_img.copy()
kernel_dilation = np.ones((5,5), np.uint8)
dilation = cv2.dilate(cv_img, kernel_dilation, iterations=12)
ret, thresh = cv2.threshold(dilation, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]
max_area = cv2.contourArea(cnt)
for cont in contours:
if cv2.contourArea(cont) > max_area:
cnt = cont
max_area = cv2.contourArea(cont)
cv2.drawContours(im_copy, [cnt], 0, (255, 255, 0), 3)
cv2.imshow('Contour', im_copy)
cv2.waitKey(0)