如何使矩形透明?

问题描述

所以我正在使用opencv,我想做一种选择工具,但是问题是不能使矩形透明。这是代码

import numpy as np
import cv2 as cv
drawing = False

def draw_rec(event,x,y,flags,param):
    global ix,iy,drawing
    if event == cv.EVENT_LBUTTONDOWN:
        drawing = True
        ix,iy = x,y
    elif event == cv.EVENT_LBUTTONUP:
        drawing = False
        cv.rectangle(img,(ix,iy),(x,y),(0,0),-1)
    elif event == cv.EVENT_MOUSEMOVE:
        if drawing == True:
            cv.rectangle(img,255,5)
img = cv.imread('baboon.jpg',-1)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_rec)
while(1):
    cv.imshow('image',img)
    k = cv.waitKey(1) & 0xFF
    if k == 27:
        break
cv.destroyAllWindows()

解决方法

代码中的第一个错误是:

elif event == cv.EVENT_LBUTTONUP:
        drawing = False
        cv.rectangle(img,(ix,iy),(x,y),(0,0),-1)

-1参数表示填充矩形。 source如果我们将-1更改为1:

enter image description here

从我的角度来看,结果并不令人满意。多矩形显示由mouse_movement引起。

elif event == cv.EVENT_MOUSEMOVE:
        if drawing == True:
            cv.rectangle(img,255,5)

每次鼠标移动时,都会绘制一个矩形。我认为最好在鼠标移动结束后进行绘制:

enter image description here

代码:


import numpy as np
import cv2 as cv
drawing = False

def draw_rec(event,x,y,flags,param):
    global ix,iy,drawing
    if event == cv.EVENT_LBUTTONDOWN:
        drawing = True
        ix,iy = x,y
    elif event == cv.EVENT_LBUTTONUP:
        drawing = False
        cv.rectangle(img,5)


img = cv.imread('27BR1.jpg',-1)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_rec)
while(1):
    cv.imshow('image',img)
    k = cv.waitKey(1) & 0xFF
    if k == 27:
        break
cv.destroyAllWindows()