gpt4 book ai didi

python - 如何使用opencv填充整个内部轮廓

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:08 25 4
gpt4 key购买 nike

在下图中,我试图将名称为“jupiter”的内部设计带涂黑

enter image description here

enter image description here

我想要的结果如下

enter image description here

我试过先使用 RETR_EXTERNAL,然后再使用 fillPoly,但它只会使二进制图像的“白色”部分(带)变黑,而不是完全按照我的意愿进行。

我需要怎样即兴创作才能让它完全变黑?

enter image description here

enter image description here

最佳答案

您可以使用屏蔽技术来完成您的工作。这是我的代码:

import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
import copy
%matplotlib inline

#-----------------------------------------------------------------------------------
I = cv2.imread('E:\\Mukul\\others\\stof.png') #input image
#I.shape

I_cnt = np.where(I[:,:,2] == 255) #location of your bounding box region
I_mask = np.zeros_like(I[:,:,2]) # mask for the input image

I_mask[list(I_cnt[0]), list(I_cnt[1])] = 255
plt.imshow(I_mask, cmap = 'gray')

bounding box region

I_cnt1, _ = cv2.findContours(I_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
np.array(I_cnt1).shape # (1, 1420, 1, 2)


cv2.fillConvexPoly(I_mask, I_cnt1[0], 255)
plt.imshow(I_mask,cmap = 'gray')

masked bounding box

因为我们希望我们的边界框区域是黑色的,我们将使用 cv2.bitwise_not() 反转我们的图像,然后使用 cv2.bitwise_and() 来获得所需的输出图像。

I_mask1 = cv2.bitwise_not(I_mask) 
out = cv2.bitwise_and(I_mask1, I[:,:,2])
plt.imshow(out,cmap = 'gray')

output image

我们可以直接转换 I_cnt[0](包含 x 的数组-coordinate) 和 I_cnt[1](包含 y 坐标的数组)到 (x,y) 坐标数组,使用以下代码:

temp_list = []
for a, b in zip(I_cnt[0], I_cnt[1]):
temp_list.append([a, b])
ctr = np.array(temp_list).reshape((-1,1,2)).astype(np.int32)

I_mask2 = np.zeros_like(I[:,:,2])
I_mask2[list(I_cnt[0]), list(I_cnt[1])] = 255
plt.imshow(I_mask2, cmap = 'gray')


cv2.fillConvexPoly(I_mask1, ctr, 255)
plt.imshow(I_mask2,cmap = 'gray')

关于python - 如何使用opencv填充整个内部轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54516877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com