首页 > 解决方案 > 如何改变盒子的不透明度(cv2.rectangle)?

问题描述

我在 OpenCV 中绘制了一些矩形并将文本放入其中。我的一般方法如下所示:

# Draw rectangle    p1(x,y)    p2(x,y)    Student name box
cv2.rectangle(frame, (500, 650), (800, 700), (42, 219, 151), cv2.FILLED )
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (510, 685), font, 1.0, (255, 255, 255), 1

到目前为止一切正常。唯一的问题是,所有框的不透明度都是 100%。我的问题是:如何更改不透明度?

最终结果应如下所示:

期望的结果

标签: pythonopencv

解决方案


我想为@HansHirse 答案添加一个小优化,我们可以先从 src 图像中裁剪矩形,然后将其与cv2.addWeighted结果交换,而不是为整个图像创建画布:

import cv2
import numpy as np

img = cv2.imread("lena.png")

# First we crop the sub-rect from the image
x, y, w, h = 100, 100, 200, 100
sub_img = img[y:y+h, x:x+w]
white_rect = np.ones(sub_img.shape, dtype=np.uint8) * 255

res = cv2.addWeighted(sub_img, 0.5, white_rect, 0.5, 1.0)

# Putting the image back to its position
img[y:y+h, x:x+w] = res

在此处输入图像描述


推荐阅读