Search code examples
pythonopencvimage-processingcomputer-visionhaar-classifier

transparent mask on a photo with coordinates of the square


I need, from an image with a square inside and coordinates, to create a transparent mask. Unfortunately I didn't find anything about the transparency literature in openCV.

For example I have this photo:

this photo

With the code below the coordinates for the square are the following

(237, 150, 311, 150, 74) - here's the code

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

I think the problem is related to the creation of the

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

All the values of the matrix are [0,0,0], how can I turn them into transparent values?

P.S. the starting extension of the photo is .jpg


Solution

  • You are almost there, now use 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
    

    example:

    enter image description here