【问题标题】:How do I make an inverse filled transparent rectangle with OpenCV?如何使用 OpenCV 制作一个反向填充的透明矩形?
【发布时间】:2020-02-28 17:27:09
【问题描述】:

我想在这张图片中做一个反向填充的矩形。

我的代码:

import cv2

lena = cv2.imread('lena.png')

output = lena.copy()
cv2.rectangle(lena, (100, 100), (200, 200), (0, 0, 255), -1)
cv2.addWeighted(lena, 0.5, output, 1 - .5, 0, output)

cv2.imshow('', output)

我想要什么:

【问题讨论】:

  • 一种可能性是在整个图像的副本上绘制您的叠加层,然后将您希望不受影响的矩形从原来的顶部复制回来。

标签: python image opencv image-processing


【解决方案1】:

我会这样做:

# initialize output
output = np.zeros_like(lena, dtype=np.uint8)
output[:,:,-1] = 255

# this is your box top_x
tx,ly,bx,ry = 100,100,200,200

# copy lena to output
output[tx:bx,ly:ry] = lena[tx:bx,ly:ry]

cv2.addWeighted(lena, 0.5, output, 1 - .5, 0, output);

输出:

【讨论】:

    【解决方案2】:

    这是在 Python/OpenCV 中执行此操作的另一种方法。虽然它不如 Quang Hoang 的解决方案优雅。

    • 读取输入
    • 创建一个相同大小的红色图像
    • 将红色图像与输入混合
    • 为“洞”创建一个带有黑色矩形的白色图像
    • 使用蒙版组合混合图像和原始图像
    • 保存结果

    输入:

    import cv2
    import numpy as np
    
    # read image
    img = cv2.imread('lena.jpg')
    
    # create red image
    red = np.full_like(img,(0,0,255))
    
    # add red to img and save as new image
    blend = 0.5
    img_red = cv2.addWeighted(img, blend, red, 1-blend, 0)
    
    # create white image for mask base
    mask = np.full_like(img, (1,1,1), dtype=np.float32)
    
    # define rectangle for "hole" and draw as black filled on the white base mask
    x1,y1,x2,y2 = 100,100,200,200
    mask = cv2.rectangle(mask, (x1, y1), (x2, y2), (0, 0, 0), -1)
    
    # combine img and img_red using mask
    result = cv2.add(img*(1-mask),img_red*mask).astype(np.uint8)
    
    cv2.imshow('img', img)
    cv2.imshow('red', red)
    cv2.imshow('img_red', img_red)
    cv2.imshow('mask', mask)
    cv2.imshow('result', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    # save results
    cv2.imwrite('lena_hole_mask.jpg', (255*mask).astype(np.uint8))
    cv2.imwrite('lena_plus_red.jpg', result)
    


    面具:

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2020-04-27
      • 2020-04-07
      • 1970-01-01
      相关资源
      最近更新 更多