如何从 PNG 图像中删除第 4 个通道
How to remove 4th channel from PNG images
我正在从 OpenCV 中的 URL 加载图像。一些图像是 PNG 格式并且有四个通道。我正在寻找一种方法来删除第 4 个通道(如果存在)。
这是我加载图像的方式:
def read_image_from_url(self, imgurl):
req = urllib.urlopen(imgurl)
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
return cv2.imdecode(arr,-1) # 'load it as it is'
我不想更改 cv2.imdecode(arr,-1)
,而是想检查加载的图像是否有第四个通道,如果有,请将其删除。
类似这样,但我不知道如何真正删除第 4 个频道
def read_image_from_url(self, imgurl):
req = urllib.urlopen(imgurl)
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
image = cv2.imdecode(arr,-1) # 'load it as it is'
s = image.shape
#check if third tuple of s is 4
#if it is 4 then remove the 4th channel and return the image.
读这个:http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html
cv2.imdecode(buf, 标志)
如果 flags < 0,如您的情况 (-1),您将按原样获得图像。
如果 flags > 0 它将 return 一个 3 通道图像。 Alpha 通道被剥离。
flags == 0 将产生灰度图像
cv2.imdecode(arr,1)
应产生 3 通道输出。
您需要检查来自 img.shape
的频道数量,然后相应地进行:
# In case of grayScale images the len(img.shape) == 2
if len(img.shape) > 2 and img.shape[2] == 4:
#convert the image from RGBA2RGB
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
这也可以。
if len(img.shape) > 2 and img.shape[2] == 4:
#slice off the alpha channel
img = img[:, :, :3]
引用
我正在从 OpenCV 中的 URL 加载图像。一些图像是 PNG 格式并且有四个通道。我正在寻找一种方法来删除第 4 个通道(如果存在)。
这是我加载图像的方式:
def read_image_from_url(self, imgurl):
req = urllib.urlopen(imgurl)
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
return cv2.imdecode(arr,-1) # 'load it as it is'
我不想更改 cv2.imdecode(arr,-1)
,而是想检查加载的图像是否有第四个通道,如果有,请将其删除。
类似这样,但我不知道如何真正删除第 4 个频道
def read_image_from_url(self, imgurl):
req = urllib.urlopen(imgurl)
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
image = cv2.imdecode(arr,-1) # 'load it as it is'
s = image.shape
#check if third tuple of s is 4
#if it is 4 then remove the 4th channel and return the image.
读这个:http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html
cv2.imdecode(buf, 标志)
如果 flags < 0,如您的情况 (-1),您将按原样获得图像。 如果 flags > 0 它将 return 一个 3 通道图像。 Alpha 通道被剥离。 flags == 0 将产生灰度图像
cv2.imdecode(arr,1)
应产生 3 通道输出。
您需要检查来自 img.shape
的频道数量,然后相应地进行:
# In case of grayScale images the len(img.shape) == 2
if len(img.shape) > 2 and img.shape[2] == 4:
#convert the image from RGBA2RGB
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
这也可以。
if len(img.shape) > 2 and img.shape[2] == 4:
#slice off the alpha channel
img = img[:, :, :3]
引用