Search code examples
pythonopencvdeep-learningsemantic-segmentation

Read 4 channel images with CV2 for Semantic segmentation


I'I'm working on a Unet semantic segmentation project where I need to process 4-channel images using OpenCV in Python, and I'm new to this field. I found a tutorial on YouTube (link to tutorial) for the same purpose, but the code provided in the tutorial uses RGB and cv2.imread() to read images, which I believe doesn't work for 4-channel images.

My goal is to adapt the provided code to work with 4-channel images, but I'm not sure how to modify it accordingly.

Here's a simplified version of the code from the tutorial:

import os
import cv2
from matplotlib import pyplot as plt

temp_img = cv2.imread('C:/Users/PREDATOR/Desktop/4_channel_image.tif')
temp_img = cv2.cvtColor(temp_img,cv2.COLOR_BGR2RGB)
plt.imshow(temp_img)

and this the error:

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
Cell In[5], line 2
      1 temp_img = cv2.imread('C:/Users/PREDATOR/Desktop/4_channel_image.tif')
----> 2 temp_img = cv2.cvtColor(temp_img,cv2.COLOR_BGR2RGB)
      3 plt.imshow(temp_img) #change 0 to 1 2 or 3 to view other channels"""
    

error: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:196: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

Solution

  • I tried the code below and it worked:

    import os
    import tifffile
    from matplotlib import pyplot as plt
    
    temp_img = tifffile.imread('C:/Users/PREDATOR/Desktop/4_channel_image.tif')
    plt.imshow(temp_img)