将RGB图像拆分为R、G、B通道 - Python

5
我正在处理图像,我想知道这段代码是否会将彩色图像分成不同的通道,并给出平均值。因为当我尝试时,它会给我读取到的图像,它会给我蓝色、绿色、红色值,以及平均值。但是当我尝试将其附加到列表中并尝试打印时,列表中只包含零。
以下是我的代码:
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)
< p > re_img1 是经过调整大小的图片(即256x256)。 图片可以是任何东西。 我在两个不同的函数中使用相同的代码,而且我遇到了同样的问题。

欢迎任何建议! 预先感谢!


2
re_img1.size是一个元组,对吧?(大小x,大小y)如果是这样,那么您的sum(x) / re_img1.size操作将无法正常工作。 - Amazingred
前往Scipy(但下面的答案是正确的,您正在将int除以元组),您可以访问许多图像处理函数,从直方图到类似于OpenCV的算法。 - cox
@Amazingred 不,它显示一个值为“196608”,没有任何花括号。 - varsha_holla
3个回答

6

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

  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)
    

希望这对你有用。 干杯!


0

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

ttl = re_img1.size

转换为:

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

由于img.size是一个元组(x,y),您正在尝试一种无效的操作(除以元组),这就是为什么您会得到那个结果。


我正在将所有的图像调整为统一尺寸(256x256)。但是它并没有起作用,反而给我一个错误:"TypeError: 'int' object has no attribute 'getitem'"。 - varsha_holla

0

从PIL库导入Image模块 tim = Image tim("leonard_de_vinci.jpg") 展示


你能加一些解释和代码上下文吗? - Lover of Structure
您提供的答案目前不够清晰。请进行[编辑]以添加更多详细信息,以帮助其他人了解如何回答问题。您可以在帮助中心找到有关编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接