2016-04-26 243 views
1

我從OpenCV中的URL加載圖像。有些圖像是PNG,有四個通道。我正在尋找一種方法來刪除第4頻道,如果它存在。如何從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. 

回答

2

您需要檢查從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) 
0

閱讀:http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html

cv2.imdecode(BUF,旗)

如果標誌是< 0與你的情況(-1)一樣,你將得到原樣的圖像。 如果標誌> 0,它將返回一個3通道圖像。 alpha通道被剝離。 標誌== 0將產生灰度圖像

cv2.imdecode(arr,1)應產生3通道輸出。

+0

是啊,有我想AS -IS某些圖像。這就是爲什麼我不願意改變國旗,而是做一個檢查,如果有第四層,然後才刪除它。 – Anthony

+0

那麼你應該問如何檢查是否有第四個頻道,而不是如何刪除它...... – Piglet

+0

這個標誌也會影響比特深度,所以這不是一個很好的解決方法來移除alpha通道 –