如何更改框的不透明度(cv2.rectangle)? [英] How to change the opacity of boxes (cv2.rectangle)?

查看:104
本文介绍了如何更改框的不透明度(cv2.rectangle)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 OpenCV 中绘制了一些矩形并将文本放入其中.我的一般方法是这样的:

I draw some rectangles in OpenCV and put text in them. My general approach looks like this:

# 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%.我的问题是:如何更改不透明度?

Everything works so far. The only thing is, that the opacity in all boxes is at 100 %. My question is: How can I change the opacity?

最终结果应该是这样的:

The final result should look like this:

推荐答案

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

I would like to add a small optimization to the @HansHirse answer, Instead of creating the canvas for whole image, we can crop the rectangle first from the src image and then later swap it with the cv2.addWeighted result as:

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

这篇关于如何更改框的不透明度(cv2.rectangle)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆