如何使用 Python 沿轮廓边界裁剪图像

时间:2021-04-18 06:17:12

标签: python opencv image-processing python-imaging-library

我基本上有数以千计的带有黑色轮廓的人物图像,所有这些图像要么有白色背景,要么有一些图形背景,通常只有后面的木质纹理。

我想要的是创建一个函数(opencv/pil/whatever),它允许我自动裁剪这些图像,基本上删除角色轮廓之外的所有内容。

Here's an example

左侧是未裁剪的原始图像,右侧是裁剪后的图像。这甚至可能吗?

1 个答案:

答案 0 :(得分:1)

使用简单的方法,您可以完成大部分工作。假设背景中没有任何黑色,我们可以通过遮蔽黑色来寻找轮廓字符。

enter image description here

然后我们要填充轮廓内的所有内容

enter image description here

最后我们可以把面具外面的所有东西都涂白

enter image description here

这张特定图片的明显问题是我们最终捕捉到了豆先生手臂中封闭的背景。我没有看到解决这个问题的简单方法。我们可以在遮罩内的区域尝试一些颜色直方图匹配;尝试寻找与遮罩外区域具有相同颜色配置文件的遮罩内区域,但这将比当前呈现的代码复杂得多。

如果当前方法适用于您的大部分图像,并且您可以轻松地手动编辑其余图像,请这样做。如果作为答案确实不可接受,请告诉我,如果有时间,我会尝试解决它。​​

import cv2
import numpy as np

# load image
img = cv2.imread("outlined.png");

# mask for black
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
mask = cv2.inRange(gray, 0, 50);

# find contours (this is using OpenCV 3, if you're using OpenCV 2 or 4, then it returns as [contours, _])
_, contours, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE);

# reset and fill mask
mask[:] = 0;
for con in contours:
    mask = cv2.drawContours(mask, [con], -1, 255, -1);

# redraw image using mask
img[mask != 255] = (255,255,255);

# show
cv2.imshow("Image", img);
cv2.imshow("Mask", mask);
cv2.waitKey(0);