python - 如何在Python中绘制半透​​明矩形?

标签 python python-3.x opencv python-imaging-library

我想要实现类似于以下内容:enter image description here

我目前在红色背景上显示图像,但不确定如何在上面的图像上绘制半透明矩形以放置文本,以使其弹出更多。我很确定可以使用OpenCV来实现,但是我对Python还是陌生的,这似乎很令人困惑。 (我似乎做得不好,开始惹恼我)。这是我当前的图像(忽略白色轮廓):

enter image description here

最佳答案

这是在Python / OpenCV中获得相同结果的一种方法。

  • 读取输入的
  • 裁剪所需区域以使
  • 变暗
  • 创建相同大小的黑色图像
  • 混合两个图像(裁剪75%和黑色25%)
  • 在混合图像上绘制文本
  • 将文本图像复制回输入
  • 中的相同位置
  • 保存结果

  • 输入:

    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()
    

    结果:

    enter image description here

    关于python - 如何在Python中绘制半透​​明矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61150743/

    相关文章:

    python - Django 按年分页

    python - 为什么 easy_install 可以正确修改 Python 模块加载路径,而 pip 和 .tar.gz 源却不能?

    python - 检查 Pandas 中的单个单元格值是否为 NaN

    python - 如何只访问列表的特定元素

    numpy - RGB到HSV的numpy

    python - Spark 无法 pickle method_descriptor

    python - 具有Autobahn,ApplicationRunner和ApplicationSession的多线程

    python - 将图形嵌入 GUI(Qtdesigner 和 Pyside)

    python-3.x - 使用Python捕获屏幕/窗口内容

    opencv - 如何计算两个旋转矩形的重叠率?