2

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

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
Da Nio
  • 302
  • 1
  • 6
  • 16

1 Answers1

3

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

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • It works, it is perfect, but I need a different solution, I need a method that eliminates the pixels outside the square (like alpha channel), or make them turn white :) – Da Nio Jul 05 '19 at 12:40
  • Then create a white photo instead of the black one in your code? – Quang Hoang Jul 05 '19 at 12:41
  • Yay, I set the value to 1000 and it turns white. I just need a solution that creates a new photo of the known square :) – Da Nio Jul 05 '19 at 12:42
  • Wouldn't `img[y:y+h,x:x+w].copy()` give you the photo of the square? – Quang Hoang Jul 05 '19 at 12:45