在Python3中彼此创建遮罩或边界

时间:2020-04-23 08:52:26

标签: python-3.x opencv mask scikit-image cv2

我想从具有边界的图像中获取蒙版,或者从蒙版图像中获取边界。

这是两张图片:

Mask Image Boundary Image

我经历了以下事情,我不明白那里的逻辑: link1link2link3link4

谢谢, 伊利亚斯

2 个答案:

答案 0 :(得分:0)

link中的人可以使用以下内容;

从蒙版获取边界:

im = cv2.imread('mask.png')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
tmp = np.zeros_like(im)
boundary = cv2.drawContours(tmp, contours, -1, (255,255,255), 1)
boundary[boundary > 0] = 255
plt.imsave("mask_boundary.png", boundary, cmap = "gray")

enter image description here

答案 1 :(得分:0)

我仍然不了解其逻辑,但是,人们可以根据遮罩创建边界,也可以根据边界创建遮罩。

import os
import numpy as np
import cv2
from matplotlib import pyplot as plt

out = "mask_boundary.png"
inp = "mask.png"
im = cv2.imread(inp)
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
tmp = np.zeros_like(im)
boundary = cv2.drawContours(tmp, contours, -1, (255,255,255), 1)
plt.imsave(out, boundary, cmap = "gray")


out = "boundary_mask.png"
inp = "mask_boundary.png"
im = cv2.imread(inp)
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,0,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
tmp = np.zeros_like(im)
boundary = cv2.drawContours(tmp, contours, 0,(255,255,255), -1)
for i in range(1,len(contours)):
    boundary = cv2.drawContours(boundary, contours, i,(255,255,255), -1)

plt.imsave(out, boundary, cmap = "gray")



out = "boun_mask.png"
inp = "boundary.png"
im = cv2.imread(inp)
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,0,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
tmp = np.zeros_like(im)
boundary = cv2.drawContours(tmp, contours, 0,(255,255,255), -1)
for i in range(1,len(contours)):
    boundary = cv2.drawContours(boundary, contours, i,(255,255,255), -1)

plt.imsave(out, boundary, cmap = "gray")

注意:使用上面的蒙版图像,我首先创建了边界,然后从该边界创建了蒙版。但是,我无法将上方的所有边界都转换为蒙版,尤其是图像边缘/边界处的蒙版。看起来边界也必须有边界! 任何帮助,我们将不胜感激!

将上述蒙版转换为边界:

mask2boundary

现在将新边界转换为蒙版:

newboundary2mask

现在将以上边界转换为蒙版:

enter image description here