import numpy as np
import cv
from PIL import Image
# open the image
img = Image.open('./pic.png', 'r')
r,g,b, alpha_channel = img.split()
mask = np.array(alpha_channel)
# all elements in alpha_channel that have value 0
# are set to 1 in the mask matrix
mask[alpha_channel==0] = 1
# all elements in alpha_channel that have value 100
# are set to 0 in the mask matrix
mask[alpha_channel==100] = 0
credit to other posts:
How to get alpha value of a PNG image with PIL?
Converting numpy array having image data to CvMat
To convert numpy array to cvmat do:
cv_arr = cv.fromarray(mask)
Check the dtype of mask. It should be dtype('uint8')
When I convert it my cv_arr is
cvmat(type=42424000 8UC1 rows=1245 cols=2400 step=2400 )
I am not an expert in opencv, but it seems to me that 8UC1 is automatically selected based on the fact that dtype is uint8 (I am guessing here because I couldn't find the documentation about that).