0

I am using OpenCV in Python.

I am trying to create a Mask Matrix variable to be used in this function: cv.minMaxLoc. The Matrix variable should have the same size like my template image, with type = CV_8UC1.

My template image has a alpha channel which consists of only 0% or 100% transparency pixels. How can I extract the alpha channel data from my image and put it into the Mask Matrix with 0 = 100% transparency and 1 = 0% transparency?

1 Answer 1

1
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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.