简体   繁体   English

在opencv python(cv2)中调整透明图像的大小

[英]resize transparent image in opencv python (cv2)

I have an image with shape (120, 470, 4) and I want to resize it to another size eg (100, 400, 4). 我有一个形状的图像(120,470,4),我想把它调整到另一个大小,例如(100,400,4)。 I try to achieve it by using cv2.resize function as bellow 我试着通过使用cv2.resize函数来实现它

reshaped_image = cv2.resize(image, (100, 400))

and paste the reshaped_image inside a bigger transparent image, but the problem is reshaped_image has the shape (100, 400, 3) instead of (100, 400, 4). 并将reshaped_image粘贴到更大的透明图像中,但问题是reshaped_image具有形状(100,400,3)而不是(100,400,4)。

Is there something wrong I'm doing or the cv2.resize function will lose transparency information? 我正在做什么问题或者cv2.resize函数会丢失透明度信息吗? And at last I'll be pleased to know about your solution. 最后,我很高兴知道您的解决方案。 (with simple example if possible) (如果可能,用简单的例子)

regards 问候

Here is an example which loads a 3 channel image, takes its blue channel and copies it as alpha channel (which makes no sense at all, but I had no 4 channel image at hand) and merges it again as a 4 channel image. 下面是一个加载3通道图像的示例,将其蓝色通道复制为alpha通道(根本没有任何意义,但我手边没有4通道图像)并将其再次合并为4通道图像。 Then this image is resized. 然后调整此图像的大小。

If you load a 4 channel image, the flag -1 indicates that the image is loaded unchanged, so you can load and split all 4 channels directly. 如果加载4通道图像,则标志-1表示图像未加载,因此您可以直接加载和拆分所有4个通道。

Shapes of all images are printed, and resizing works. 打印所有图像的形状,并调整大小。 I am working opencv version 3.1.0. 我正在使用opencv 3.1.0版。

Hope that helps. 希望有所帮助。

import cv2
import numpy as np

img = cv2.imread('image.jpg', -1)
print img.shape

b_channel, g_channel, r_channel = cv2.split(img)
alpha_channel = b_channel 
print b_channel.shape
print g_channel.shape
print r_channel.shape
print alpha_channel.shape

img_RGBA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
print img_RGBA.shape

res = cv2.resize(img_RGBA,(100, 400), interpolation = cv2.INTER_CUBIC)
print res.shape

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM