[英]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.
您需要從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]
參考帖
請閱讀以下內容: http : //docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html
cv2.imdecode(buf,標志)
如果flags <0(如您的情況(-1)),則將按原樣獲取圖像。 如果flags> 0,它將返回一個3通道圖像。 alpha通道被剝離。 標志== 0將產生灰度圖像
cv2.imdecode(arr,1)
應產生3通道輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.