Dylan Shaw
Dylan Shaw

Reputation: 45

How do I draw a semi-transparent rectangle in Python?

I would like to achieve something similar to this:enter image description here

I currently have the image on the red background but I am unsure how to draw a translucent rectangle such as on the image above to put the text on in order to make it pop out more. I’m pretty sure it can be achieved using OpenCV but I am fairly new to Python and it seems very confusing. (I can’t seem to do it properly and it’s starting to annoy me). Here is my current image (ignore the white outline):

enter image description here

Upvotes: 1

Views: 2785

Answers (1)

fmw42
fmw42

Reputation: 53164

Here is one way to achieve the same results in Python/OpenCV.

  • Read the input
  • Crop the desired region to darken
  • Create the same sized black image
  • Blend the two image (crop 75% and black 25%)
  • Draw text on the blended image
  • Copy the text image back to the same location in the input
  • Save results

Input:

enter image description here

import cv2
import numpy as np

# load image
img = cv2.imread("chimichanga.jpg")

# define undercolor region in the input image
x,y,w,h = 66,688,998,382

# define text coordinates in the input image
xx,yy = 250,800

# compute text coordinates in undercolor region
xu = xx - x
yu = yy - y

# crop undercolor region of input
sub = img[y:y+h, x:x+w]

# create black image same size
black = np.zeros_like(sub)

# blend the two
blend = cv2.addWeighted(sub, 0.75, black, 0.25, 0)

# draw text on blended image
text = cv2.putText(blend, "CHIMICHANGA", (xu,yu), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), cv2.LINE_8, bottomLeftOrigin=False )

# copy text filled region onto input
result = img.copy()
result[y:y+h, x:x+w] = text

# write result to disk
cv2.imwrite("chimichanga_result.jpg", result)

# display results
cv2.imshow("BLEND", blend)
cv2.imshow("TEXT", text)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()


Result:

enter image description here

Upvotes: 2

Related Questions