将RGB图像分割为R,G,B通道 - python

时间:2014-04-21 17:12:59

标签: python image-processing rgb

我正在进行图像处理,我想知道这段代码是否会将彩色图像分成不同的通道,并给我平均值。因为当我尝试给我一张我正在阅读的图像时,它会给我蓝色,绿色,红色的值以及平均值。当我尝试将其附加到列表中并尝试打印时,该列表仅包含零'。

这是我的代码:

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是调整大小的图像(即256x256)。图像可以是任何东西。我在2个不同的功能中使用了相同的代码,我也遇到了同样的问题。

欢迎任何建议!提前谢谢!

2 个答案:

答案 0 :(得分:6)

如果我理解你,你正在尝试计算每个RGB通道的平均值。您的代码中存在两个问题:

  1. ttl 应除以3,如下所示,否则它是X通道的像素数(例如:对于256X256 RGB,即196608)
  2. 代码中的
  3. b,g和r 实际上是 numpy.ndarray 类型,因此您应该使用适当的方法来操作它们,< em> ie ndarray.sum 。将总和设为浮点数,否则您将丢失小数,因为2个整数的商将给你一个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)
    
  4. 希望这对你有用。 干杯!

答案 1 :(得分:1)

我认为你需要做的就是改变这个:

ttl = re_img1.size

到此:

ttl = re_img1.size[0] #This only works correctly if the img is a perfect square

因为img.size是一个元组(x,y),你正在尝试一个无效的操作(由元组排除),这就是你获得该结果的原因。