【问题标题】:How can I cycle through individual pixels in an image and output the highest RGB valued pixel of each row?如何循环遍历图像中的单个像素并输出每行的最高 RGB 值像素?
【发布时间】:2013-07-20 22:02:06
【问题描述】:

我正在尝试导入一个图像文件,例如file.bmp,读取图像中每个像素的RGB值,然后输出每行RGB值最高的像素(最亮的像素) /em> 到屏幕上。关于如何使用 Python 来做这件事有什么建议吗?

【问题讨论】:

    标签: python image image-processing rgb


    【解决方案1】:

    您可以在这里充分利用 numpy 的强大功能。请注意,下面的代码会输出 [0, 255] 范围内的“亮度”。

    #!/bin/env python
    
    import numpy as np
    from scipy.misc import imread
    
    #Read in the image
    img = imread('/users/solbrig/smooth_test5.png')
    
    #Sum the colors to get brightness
    brightness = img.sum(axis=2) / img.shape[2]
    
    #Find the maximum brightness in each row
    row_max = np.amax(brightness, axis=1)
    print row_max
    

    如果您认为您的图像可能有 alpha 层,您可以这样做:

    #!/bin/env python
    
    import numpy as np
    from scipy.misc import imread
    
    #Read in the image
    img = imread('/users/solbrig/smooth_test5.png')
    
    #Pull off alpha layer
    if img.shape[2] == 4:
        alph = img[:,:,3]/255.0
        img = img[:,:,0:3]
    else:
        alph = np.ones(img.shape[0:1])
    
    #Sum the colors to get brightness
    brightness = img.sum(axis=2) / img.shape[2]
    brightness *= alph
    
    #Find the maximum brightness in each row
    row_max = np.amax(brightness, axis=1)
    print row_max
    

    【讨论】:

    【解决方案2】:

    好吧,您可以使用scipy.misc.imread 来读取图像并像这样操作它:

    import scipy.misc
    file_array = scipy.misc.imread("file.bmp")
    
    def get_brightness(pixel_tuple):
       return sum([component*component for component in pixel_tuple])**.5 # distance from (0, 0, 0)
    
    row_maxima = {}
    height, width = len(file_array), len(file_array[0])
    for y in range(height):
      for x in range(width):
        pixel = tuple(file_array[y][x]) # casting it to a tuple so it can be stored in the dict
        if y in row_maxima and get_brightness(pixel) > row_maxima[y]:
          row_maxima[y] = pixel
        if y not in row_maxima:
          row_maxima[y] = pixel
    print row_maxima
    

    【讨论】:

    • 当我尝试运行这段代码时,它说 "image" 没有定义:第 11 行,在 中 pixel = tuple(image[y][x]) # 将其转换为元组所以它可以存储在字典中 NameError: name 'image' is not defined 你将图像定义为什么?我是 python 新手,抱歉。
    • 哦,对不起,这是我的错字。 Image 应该是 file_array。我已经更新了。
    • 我还没有看到计算亮度的rgb距离(0,0,0)方法。我认为标准方法会使用 30% 的红色值 + 60% 的绿色值 + 10% 的蓝色值来匹配人类视觉敏感度。见sandbox.mc.edu/friendly_python/lab4.html
    猜你喜欢
    • 2013-07-16
    • 2011-12-06
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    相关资源
    最近更新 更多