简体   繁体   English

将蒙版保存到图像(Python,OpenCV)

[英]Save mask to image (Python, OpenCV)

I am using this code to create a mask which split every image in half (left-right). 我正在使用此代码创建一个遮罩,将每个图像分成两半(左右)。

import cv2
import numpy as np

image = cv2.imread('box.png')

h = image.shape[0]
w = image.shape[1]

mask_l = np.zeros(image.shape[:2], dtype="uint8")

roi = cv2.rectangle(mask_l, (w//2, 0), (0, h), 255, -1)  # LEFT MASK

masked_l = cv2.bitwise_and(image, image, mask=mask_l)
cv2.imshow("Left", masked_l)
cv2.waitKey(0)


mask_r = np.zeros(image.shape[:2], dtype="uint8")

cv2.rectangle(mask_r, (w//2, 0), (w, h), 255, -1)  # RIGHT MASK

masked_r = cv2.bitwise_and(image, image, mask=mask_r)
cv2.imshow("Right", masked_r)
cv2.waitKey(0)

How can I save the visible part of the image to a ROI ? 如何将图像的可见部分保存到ROI? Possible, if the saved rectangle take the name as source image as part of filename. 如果保存的矩形将名称作为源图像作为文件名的一部分,则可能的。 Es: input --> box.png --> output --> box1.png, box2.png ES:输入-> box.png->输出-> box1.png,box2.png

Thanks 谢谢

I did it... 我做的...

import cv2
import numpy as np
import os

image = cv2.imread('box.png')

path, filename = os.path.split('box.png')
filename = (filename[:-4])

root_path = 'C:\\Users\\Link\\Desktop\\'

h = image.shape[0]
w = image.shape[1]

mask_l = np.zeros(image.shape[:2], dtype="uint8")

roi = cv2.rectangle(mask_l, (w//2, 0), (0, h), 255, -1)  # LEFT MASK

masked_l = cv2.bitwise_and(image, image, mask=mask_l)

list = ['a', 'b']

for i in enumerate(masked_l):
    x, y, w, h = cv2.boundingRect(mask_l)
    roi_l = image[y:y + h, x:x + w]
    cv2.imwrite(root_path + str(filename) + '{}.png'.format(lista[0]), roi_l)

cv2.imshow("Left", roi_l)
cv2.waitKey(0)


h2 = image.shape[0]
w2 = image.shape[1]

mask_r = np.zeros(image.shape[:2], dtype="uint8")

cv2.rectangle(mask_r, (w2//2, 0), (w2, h2), 255, -1)  # RIGHT MASK

masked_r = cv2.bitwise_and(image, image, mask=mask_r)

for i_i in enumerate(masked_r):
    x2, y2, w2, h2 = cv2.boundingRect(mask_r)
    roi_r = image[y2:y2 + h2, x2:x2 + w2]

    cv2.imwrite(root_path + str(filename) + '{}.png'.format(lista[1]), roi_r)

cv2.imshow("Right", roi_r)
cv2.waitKey(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM