[英]How to create Mask matrix variable for OpenCV minMaxLoc function in Python?
I am using OpenCV in Python. 我在Python中使用OpenCV。
I am trying to create a Mask
Matrix variable to be used in this function: cv.minMaxLoc . 我正在尝试创建要在此函数中使用的Mask
Matrix变量: cv.minMaxLoc 。 The Matrix variable should have the same size like my template image, with type = CV_8UC1
. Matrix变量应具有与我的模板图像相同的大小,类型为= CV_8UC1
。
My template image has a alpha channel which consists of only 0%
or 100%
transparency pixels. 我的模板图像具有一个Alpha通道,该通道仅包含0%
或100%
透明像素。 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
? 如何从图像中提取Alpha通道数据并将其以0 = 100% transparency
和1 = 0% transparency
放入Mask
Matrix中?
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? 归功于其他帖子: 如何使用PIL获取PNG图像的Alpha值? Converting numpy array having image data to CvMat 将具有图像数据的numpy数组转换为CvMat
To convert numpy array to cvmat do: 要将numpy数组转换为cvmat,请执行以下操作:
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 ) 它应该是dtype('uint8')转换时,我的cv_arr是cvmat(type = 42424000 8UC1行= 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). 我不是opencv的专家,但是在我看来dtype是uint8是自动选择8UC1的原因(我在这里是因为找不到相关的文档)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.