在Python3中互相创建遮罩或边界

问题描述 投票:0回答:2

我想从具有边界或边界的图像中获取掩模。

这里有两个图像:

Mask ImageBoundary Image

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

谢谢,伊利亚斯

python-3.x opencv mask scikit-image cv2
2个回答
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


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

© www.soinside.com 2019 - 2024. All rights reserved.