概念
-
检测物体的轮廓。
-
遍历轮廓并找到包围图像中心的轮廓。
-
使用该轮廓,为图像创建蒙版并蒙版。
代码
import cv2
import numpy as np
def process(img):
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_canny = cv2.Canny(img_gray, 0, 50)
img_dilate = cv2.dilate(img_canny, None, iterations=1)
img_erode = cv2.erode(img_dilate, None, iterations=1)
return img_erode
def get_masked(img):
h, w, _ = img.shape
center = h // 2, w // 2
contours, _ = cv2.findContours(process(img), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
if cv2.contourArea(cnt) > 100:
if cv2.pointPolygonTest(cnt, center, False) > 0:
mask = np.zeros((h, w), 'uint8')
cv2.drawContours(mask, [cnt], -1, 255, -1)
return cv2.bitwise_and(img, img, mask=mask)
img = cv2.imread("blobs.png")
cv2.imshow("img_processed", get_masked(img))
cv2.waitKey(0)
输出
解释
- 导入必要的库:
import cv2
import numpy as np
- 定义一个函数将图像处理成二值图像,以便在检测图像轮廓时获得最佳结果:
def process(img):
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_canny = cv2.Canny(img_gray, 0, 50)
img_dilate = cv2.dilate(img_canny, None, iterations=1)
img_erode = cv2.erode(img_dilate, None, iterations=1)
return img_erode
- 定义一个循环遍历图像轮廓的函数(使用之前定义的
process函数来处理图像),并且对于轮廓面积大于100的每个轮廓 em>(滤除噪声),检查图像的中心是否在轮廓内(通过检查调用cv2.pointPolygonTest的结果是否返回正数来完成),创建遮罩,遮罩图像并返回遮罩图像:
def get_masked(img):
h, w, _ = img.shape
center = h // 2, w // 2
contours, _ = cv2.findContours(process(img), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
if cv2.contourArea(cnt) > 100:
if cv2.pointPolygonTest(cnt, center, False) > 0:
mask = np.zeros((h, w), 'uint8')
cv2.drawContours(mask, [cnt], -1, 255, -1)
return cv2.bitwise_and(img, img, mask=mask)
- 最后,读入你的图片,应用之前定义的
get_masked函数并显示图片:
img = cv2.imread("blobs.png")
cv2.imshow("img_processed", get_masked(img))
cv2.waitKey(0)