如何在Python中为OpenCV的minMaxLoc函数创建掩码矩阵变量?
我正在使用Python中的OpenCV库。
我想创建一个叫做Mask
的矩阵变量,用来在这个函数中使用:cv.minMaxLoc。这个矩阵变量的大小要和我的模板图像一样,类型要设置为CV_8UC1
。
我的模板图像有一个透明度通道,这个通道的像素值只有0%
(完全透明)或100%
(完全不透明)。我该如何从我的图像中提取透明度通道的数据,并把它放到Mask
矩阵中,使得0
代表100%
透明度,1
代表0%
透明度呢?
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
感谢其他帖子提供的信息: 如何用PIL获取PNG图片的透明度值? 将包含图像数据的numpy数组转换为CvMat
要将numpy数组转换为cvmat,可以这样做:
cv_arr = cv.fromarray(mask)
检查一下mask的dtype(数据类型)。它应该是dtype('uint8')。 当我进行转换时,我的cv_arr是 cvmat(type=42424000 8UC1 rows=1245 cols=2400 step=2400 )
我不是opencv方面的专家,但我觉得8UC1是根据dtype是uint8自动选择的(我在这里猜测,因为我找不到相关的文档)。