Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the opacity of boxes (cv2.rectangle)?

Tags:

python

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

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:

Desired outcome

like image 600
Francesco Avatar asked Jun 06 '19 06:06

Francesco


People also ask

How do I change opacity in OpenCV?

OpenCV's imshow() function ignores the alpha channel. If you want to see the effect of your alpha channel, save your image in PNG format (because that supports alpha channel) and display in a different viewer. I also wrote a decorator/enhancement for imshow() here that helps visualise transparent images.

How do I make an image transparent in OpenCV?

Just use a new image (e.g. white), draw on it and somehow mark where you are drawing (not needed if you don't draw white as you can check for all pixels != white). Then all non-drawed weights are zero, when you combine these two images. (I'm not an opencv user and i made some assumptions about how addWeighted works).

What is cv2 rectangle in Python?

cv2. rectangle () is used to draw a rectangle on any image. Syntax: cv2.rectangle (image, start_point, end_point, color , thickness) Parameters: image: It is the image on which rectangle is to be drawn.


1 Answers

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

enter image description here

like image 153
ZdaR Avatar answered Oct 04 '22 09:10

ZdaR