简体   繁体   English

如何使用 OpenCV 制作反向填充的透明矩形?

[英]How do I make an inverse filled transparent rectangle with OpenCV?

I want to make an inverse filled rectangle in this picture.我想在这张图片中制作一个反向填充的矩形。

在此处输入图片说明

The code I have:我有的代码:

import cv2

lena = cv2.imread('lena.png')

output = lena.copy()
cv2.rectangle(lena, (100, 100), (200, 200), (0, 0, 255), -1)
cv2.addWeighted(lena, 0.5, output, 1 - .5, 0, output)

cv2.imshow('', output)

在此处输入图片说明

What I want:我想要的是:

在此处输入图片说明

Here's what I would do:这是我会做的:

# initialize output
output = np.zeros_like(lena, dtype=np.uint8)
output[:,:,-1] = 255

# this is your box top_x
tx,ly,bx,ry = 100,100,200,200

# copy lena to output
output[tx:bx,ly:ry] = lena[tx:bx,ly:ry]

cv2.addWeighted(lena, 0.5, output, 1 - .5, 0, output);

OUtput:输出:

在此处输入图片说明

Here is another way to do it in Python/OpenCV.这是在 Python/OpenCV 中执行此操作的另一种方法。 Though it is not as elegant as the solution from Quang Hoang.虽然它不如 Quang Hoang 的解决方案那么优雅。

  • Read the input读取输入
  • Create a red image of the same size创建相同大小的红色图像
  • Blend the red image with the input将红色图像与输入混合
  • Create a white image with a black rectangle for the "hole"为“孔”创建一个带有黑色矩形的白色图像
  • Combine the blended image and the original image using the mask使用蒙版组合混合图像和原始图像
  • Save the result保存结果

Input:输入:

在此处输入图片说明

import cv2
import numpy as np

# read image
img = cv2.imread('lena.jpg')

# create red image
red = np.full_like(img,(0,0,255))

# add red to img and save as new image
blend = 0.5
img_red = cv2.addWeighted(img, blend, red, 1-blend, 0)

# create white image for mask base
mask = np.full_like(img, (1,1,1), dtype=np.float32)

# define rectangle for "hole" and draw as black filled on the white base mask
x1,y1,x2,y2 = 100,100,200,200
mask = cv2.rectangle(mask, (x1, y1), (x2, y2), (0, 0, 0), -1)

# combine img and img_red using mask
result = cv2.add(img*(1-mask),img_red*mask).astype(np.uint8)

cv2.imshow('img', img)
cv2.imshow('red', red)
cv2.imshow('img_red', img_red)
cv2.imshow('mask', mask)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite('lena_hole_mask.jpg', (255*mask).astype(np.uint8))
cv2.imwrite('lena_plus_red.jpg', result)


Mask:面具:

在此处输入图片说明

Result:结果:

在此处输入图片说明

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

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