jsi*_*ibs 5 python opencv image image-processing computer-vision
我正在尝试找到金属光泽物体的轮廓,如下图所示:
我使用 OpenCV 的 Canny 来获取图像的轮廓;然而,结果(如下)确实绘制了原始图像的完整轮廓。右下角有一个很大的缺口。
我恳请任何类型的资源来帮助我完善轮廓,使其连续且(非常接近)与原始图像的形状相似。
一种简单的方法是应用大高斯模糊 来平滑图像,然后应用自适应阈值。假设该对象是图像中最大的物体,我们可以找到轮廓,然后使用轮廓区域过滤对最大轮廓进行排序。
二值图像
结果
代码
import cv2
import numpy as np
# Load image, convert to grayscale, Gaussian Blur, adaptive threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (13,13), 0)
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,51,7)
# Morph close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)
# Find contours, sort for largest contour, draw contour
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
for c in cnts:
cv2.drawContours(image, [c], -1, (36,255,12), 2)
break
cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)