簡體   English   中英

如何在 Python 中屏蔽任意形狀的外部或內部?

[英]How to mask outside or inside an arbitrary shape in Python?

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np
import cv2
a=np.arange(1,9)
filename = 'image_file_0.tiff'
img = cv2.imread(filename)
x = np.array([389, 392, 325, 211, 92,103,194,310])
y = np.array([184,281,365,401,333,188,127,126])
x = np.r_[x, x[0]]
y = np.r_[y, y[0]]
tck, u = interpolate.splprep([x, y], s=0, per=True)
xi, yi = interpolate.splev(np.linspace(0, 1, 1000), tck)
fig, ax = plt.subplots(1, 1)

ax.plot(xi, yi, '-b')
plt.imshow(img)
plt.show()

我的形象

我想在圖像中形成任意閉合曲線后轉換外部或內部區域的像素值。 我該怎么做?

您可以使用cv2.fillpoly function 來完成。以這張圖片為例:

在此處輸入圖像描述

我們可以使用以下方法獲得我們想要遮罩的形狀:

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np
import cv2
a=np.arange(1,9)
filename = 'image_file_0.tiff'
img = cv2.imread('image_left.png', cv2.IMREAD_COLOR)
x = np.array([289, 292, 125, 111,  40,  80, 94,210])
y = np.array([84 , 181, 265, 241,133, 88, 27,  40])
x = np.r_[x, x[0]]
y = np.r_[y, y[0]]
tck, u = interpolate.splprep([x, y], s=0, per=True)
xi, yi = interpolate.splev(np.linspace(0, 1, 1000), tck)

plt.imshow(img[:,:,[2,1,0]])
plt.scatter(xi, yi)
plt.show()

這導致: 在此處輸入圖像描述

現在可以使用以下方法完成屏蔽:

contour = np.array([[xii, yii] for xii, yii in zip(xi.astype(int), yi.astype(int))])
mask    = np.zeros_like(img)
cv2.fillPoly(mask, pts=[contour], color=(255, 255, 255))
masked_img = cv2.bitwise_and(img, mask)

結果: 在此處輸入圖像描述

使用倒置蒙版,您可以根據需要操縱外部像素:

mask    = np.ones_like(img)*255
cv2.fillPoly(mask, pts=[contour], color=(0,0,0))
masked_img = cv2.bitwise_and(img, mask)

這導致:

在此處輸入圖像描述

這是使用cv2.drawContours()的另一種方法。 這個想法是獲取粗略的輪廓點,將它們平滑,將此輪廓繪制到蒙版上,然后cv2.bitwise_and()或按位反轉 - 並提取所需的區域。


輸入圖像->生成的掩碼

結果->反轉結果

import numpy as np
import cv2
from scipy import interpolate

# Load image, make blank mask, define rough contour points
image = cv2.imread('1.jpg')
mask = np.zeros(image.shape, dtype=np.uint8) 
x = np.array([192, 225, 531, 900, 500])
y = np.array([154, 281, 665, 821, 37])
x = np.r_[x, x[0]]
y = np.r_[y, y[0]]

# Smooth contours
tck, u = interpolate.splprep([x, y], s=0, per=True)
x_new, y_new = interpolate.splev(np.linspace(0, 1, 1000), tck)
smooth_contour = np.array([[[int(i[0]), int(i[1])]] for i in zip(x_new, y_new)])

# Draw contour onto blank mask in white
cv2.drawContours(mask, [smooth_contour], 0, (255,255,255), -1)
result1 = cv2.bitwise_and(image, mask)
result2 = cv2.bitwise_and(image, 255 - mask)

cv2.imshow('image', image)
cv2.imshow('mask', mask)
cv2.imshow('result1', result1)
cv2.imshow('result2', result2)
cv2.waitKey()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM