首页 > 解决方案 > 我想水平屏蔽多个图像

问题描述

我有很少的日记页面图像,其中有两列我想在不改变维度的情况下将一列屏蔽为白色。这意味着即使有一列,输出图像也应该与输入图像具有相同的维度。

我能够遮盖图像,但遮罩部分变黑了,我想要白色。

import cv2

import numpy as np

# Load the original image

image = cv2.imread(filename = "D:\output_final_word5\image1.jpg")

# Create the basic black image 

mask = np.zeros(shape = image.shape, dtype = "uint8")

# Draw a white, filled rectangle on the mask image

cv2.rectangle(img = mask, pt1 = (0, 0), pt2 = (795, 3000), color = (255, 255, 

255), thickness = -1)

# Apply the mask and display the result

maskedImg = cv2.bitwise_and(src1 = image, src2 = mask)

#cv2.namedWindow(winname = "masked image", flags = cv2.WINDOW_NORMAL)

cv2.imshow("masked image",maskedImg)

cv2.waitKey(delay = 0)

cv2.imwrite("D:\Test_Mask.jpg",maskedImg)

我的最终目标是读取一个文件夹,其中有几个期刊页面,其中需要通过屏蔽第一列然后另一列来保存而不影响输入图像的尺寸,并且遮罩部分应该是白色的。以下是附加的输入图像...

Input_Image1

Input_Image2

和输出应该是这样的......

输出_图像1

输出_Image2

标签: pythonnumpyopencvimage-processingmask

解决方案


你不需要面具来绘制矩形。您可以直接在图像上绘制它。

您还可以使用image.copy()其他列创建第二个图像

顺便说一句:如果795在宽度的中间,那么您可以使用image.shape它来获取它(height,width)并使用它width//2来代替,795这样它将适用于具有不同宽度的图像。但如果795不是理想的中间,那么使用half_width = 795

import cv2

image_1 = cv2.imread('image.jpg')
image_2 = image_1.copy()

height, width, depth = image_1.shape # it gives `height,width`, not `width,height`
half_width = width//2
#half_width = 795

cv2.rectangle(img=image_1, pt1=(0, 0), pt2=(half_width, height), color=(255, 255, 255), thickness=-1)
cv2.rectangle(img=image_2, pt1=(half_width, 0), pt2=(width, height), color=(255, 255, 255), thickness=-1)

cv2.imwrite("image_1.jpg", image_1)
cv2.imwrite("image_2.jpg", image_2)

cv2.imshow("image 1", image_1)
cv2.imshow("image 2", image_2)

cv2.waitKey(0)
cv2.destroyAllWindows()

推荐阅读