Ant*_*ony 3 python png opencv image-processing
我正在从OpenCV中的URL加载图像。一些图像是PNG,具有四个通道。我正在寻找一种删除第四频道(如果存在)的方法。
这就是我加载图像的方式:
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'
Run Code Online (Sandbox Code Playgroud)
我不想更改,cv2.imdecode(arr,-1)但我想检查加载的图像是否有第四个通道,如果有,请删除它。
像这样,但我不知道如何删除第四个频道
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.
Run Code Online (Sandbox Code Playgroud)
您需要检查来自的通道数,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)
Run Code Online (Sandbox Code Playgroud)