Transform images to red/green channels

Is it possible to transform an PNG image to Red or Green channel during the iteration? This is to enable me differentiate between the red or green object.

Hi . I think you have gotten something wrong here. PNG is a file extension. It has nothing to do with image being RGB.

If you want to differentiate between colors you can use color thresholding.

Thanks! Do you have an example handy for this please?

Your objective here is not clear for me to give a example right away. So can you tell me more about what you are trying to do .

I have images in PNG format that i would like to perform cell counting on. Some cells are in Red and others in Green i would like to count each type separately.

I am not sure what cell are . I think they are pixels.
This maybe a long approach but this is what comes to my mind.

You will have to use OpenCV for this.

1.Transform image into HSV color space
2.Create masks for Red and Green

import cv2

image = cv2.imread('image_path')
image_copy = image.copy()
image_hsv = cv2.cvtColor(image_copy, cv2.COLOR_BGR2HSV)

green_lower = np.array([45,0,0])
green_upper = np.array([70,255,255])
mask_green = cv2.inRange(image_hsv, green_lower, green_upper)
green_cells = np.sum(mask_green)

red_lower = np.array([0,0,0])
red_upper = np.array([5,255,255])
mask_red = cv2.inRange(image_hsv, green_lower, green_upper)
red_cells = np.sum(mask_red)

Is this Okay ? :slight_smile:

1 Like

Thanks for this. In my DataLoader I have the following code. Can this be modified to reflect the above:

   def __getitem__(self, idx):
        path = self.files[idx]
        sample =
        #transform3 = Grayscale(num_output_channels=3)
        #sample = transform3(sample) # convert to a 3 channel grayscale, as it needs to be 3 channel.
        if self.transform:
            sample = self.transform(sample)


Just to clarify something, you have color images right ? (because you used a comment like this)

1 Like

Yes, they are colour images. Would it be possible to separate the channels?

I dont know how to implement above code in a DataLoader class but You dont have to implemnt it in that class.
You can separate channels after you get a batch from the DataLoader . Something like doing calculations on the fly.