首页 > 解决方案 > 带有正方形坐标的照片上的透明蒙版

问题描述

我需要从内部带有正方形和坐标的图像中创建透明蒙版。不幸的是,我在 openCV 中没有找到任何关于透明度文献的信息。

例如我有这张照片:

这张照片

使用下面的代码,正方形的坐标如下

(237, 150, 311, 150, 74) - 这是代码

def loc(photo):
    img = cv2.imread(photo,cv2.IMREAD_COLOR)
    red = rgb2redChan(img)

    #read HAAR ade loop for find eye(s)
    try:
        eyes = eye_cascade.detectMultiScale(red)
        best_ex=eyes[0][0]
        best_ey=eyes[0][1]
        best_ew=eyes[0][2]
        best_eh=eyes[0][3]
        for (ex,ey,ew,eh) in eyes:
            if(best_eh<eh):
                best_ex=ex
                best_ey=ey
                best_ew=ew
                best_eh=eh
        print(ex,ey,ex+ew,ey,eh)
        cv2.rectangle(img,(best_ex,best_ey),(best_ex+best_ew,best_ey+best_eh),(255,255,255),2)

        img = createMask(img,best_ex,best_ey,best_ew,best_eh)
    except:
        print("Not localized")

    #show eye(s) rectangle in color image
    cv2.imshow('red',img)
    #press any key to close
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return img,photo.split("/")[-1]

def createMask(img,x,y,w,h):
    mask = np.zeros(img.shape,np.uint8)
    mask[y:y+h,x:x+w] = img[y:y+h,x:x+w]
    return mask

我认为问题与创建

mask = np.zeros(img.shape,np.uint8)

矩阵的所有值都是[0,0,0],如何将它们变成透明值?

PS照片的起始扩展名是.jpg

标签: pythonopencvimage-processingcomputer-visionhaar-classifier

解决方案


你快到了,现在使用addWeighted

def createMask(img,x,y,w,h, alpha=0.5):
    '''
    update alpha to the darkness you want
    '''
    mask = np.zeros(img.shape,np.uint8)
    mask[y:y+h,x:x+w] = img[y:y+h,x:x+w]

    beta = 1 - alpha
    mask = cv2.addWeighted(img, alpha, mask, beta, 0)
    return mask

例子:

在此处输入图像描述


推荐阅读