简体   繁体   English

使用 Python OpenCV 缩小和放大轮廓图像

[英]shrink and enlarge contour image with Python OpenCV

I have an image with an object like below:我有一个像下面这样的对象的图像:

在此处输入图片说明

I can detect the contour and get a mask with only ball region, but my ROI is the edge region, that means I need a bigger and a smaller mask which combine to get this:我可以检测轮廓并得到一个只有球区域的掩码,但我的 ROI 是边缘区域,这意味着我需要一个更大和更小的掩码,结合起来得到这个:

在此处输入图片说明

so my question is: how can I shrink/enlarge the mask of contour around contour's center?所以我的问题是:如何缩小/放大轮廓中心周围的轮廓蒙版?

Here is one way to do that in Python/OpenCV.这是在 Python/OpenCV 中执行此操作的一种方法。

 - Read the input
 - Convert to grayscale
 - Threshold
 - Use morphology close and open to clean up noise and small regions to form a mask
 - Dilate the mask
 - Erode the mask
 - Merge the input and dilated mask
 - Merge the eroded mask with the previous result
 - Save the result

Input:输入:

在此处输入图片说明

import cv2
import numpy as np

# read image
img = cv2.imread("basketball.png")

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# make anything not white into black
mask = gray.copy()
mask[mask!=255] = 0

# invert mask so center is white and outside is black
mask = 255 - mask

# close open mask to clean up small regions and make 3 channels
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)

# erode mask
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (51,51))
erode = cv2.morphologyEx(mask, cv2.MORPH_ERODE, kernel)

# dilate mask and make 3 channels
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (51,51))
dilate = cv2.morphologyEx(mask, cv2.MORPH_DILATE, kernel)

# merge image onto dilated mask using mask
result = np.where(mask==(255,255,255), img, dilate)

# merge inverted erode onto result using erode
result = np.where(erode==(255,255,255), (255-erode), result)

# write result to disk
cv2.imwrite("basketball_mask.png", mask)
cv2.imwrite("basketball_eroded_mask.png", erode)
cv2.imwrite("basketball_dilate_mask.png", dilate)
cv2.imwrite("basketball_dilate_mask.png", dilate)
cv2.imwrite("basketball_result.png", result)

# display it
cv2.imshow("image", img)
cv2.imshow("mask", mask)
cv2.imshow("erode", erode)
cv2.imshow("dilate", dilate)
cv2.imshow("result", result)
cv2.waitKey(0)

Mask:面具:

在此处输入图片说明

Erode mask:腐蚀掩码:

在此处输入图片说明

Dilate mask:扩张面膜:

在此处输入图片说明

Result:结果:

在此处输入图片说明

Note: If you dilate too much, you reach the edges of the image and then the shape changes.注意:如果膨胀过多,则会到达图像的边缘,然后形状会发生变化。 To avoid that, pad the input with background color enough to contain the dilated size.为避免这种情况,请使用足以包含膨胀大小的背景颜色填充输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM