Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting an RGB image to R,G,B channels - python

I'm working on image processing, I want to know whether this code will split a color image into different channels, and give me the mean. Because when I tried its giving me the image what I'm reading, its giving me the blue, green, red values, and also the mean value. When i try to append it to a list, and try to print it, then the list contains only Zeros'.

This is my code:

b, g, r = cv2.split(re_img1)
ttl = re_img1.size
B = sum(b) / ttl
G = sum(g) / ttl
R = sum(r) / ttl
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)

re_img1 is the resized image(i.e 256x256). Image can be anything. And I'm using the same code in 2 different function, and I'm facing the same problem.

Any suggestions are welcome! Thanks in advance!

like image 946
varsha_holla Avatar asked Apr 21 '14 17:04

varsha_holla


1 Answers

If I understand you well, you are trying to calculate the mean of each RGB channel. There are 2 problems in your code:

  1. ttl should be divided by 3 as below, because otherwise it's the number of pixels X channels (ex: for a 256X256 RGB, that would be 196608)
  2. b, g, and r in your code are actually of the numpy.ndarray type, so you should use the appropriate methods to manipulate them, i.e ndarray.sum. Make the sum a float, otherwise you will lose decimals, since the quotient of 2 ints will give you an int.

    import cv2
    import numpy as np
    re_img1 = cv2.imread('re_img1.png')
    b, g, r = cv2.split(re_img1)
    
    ttl = re_img1.size / 3 #divide by 3 to get the number of image PIXELS
    
    """b, g, and r are actually numpy.ndarray types,
    so you need to use the appropriate method to sum
    all array elements"""
    B = float(np.sum(b)) / ttl #convert to float, as B, G, and R will otherwise be int
    G = float(np.sum(g)) / ttl
    R = float(np.sum(r)) / ttl
    B_mean1 = list()
    G_mean1 = list()
    R_mean1 = list()
    B_mean1.append(B)
    G_mean1.append(G)
    R_mean1.append(R)
    

Hope that's useful to you. Cheers!

like image 145
Raoul Avatar answered Oct 12 '22 01:10

Raoul