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!
If I understand you well, you are trying to calculate the mean of each RGB channel. There are 2 problems in your code:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With