【发布时间】:2013-07-20 22:02:06
【问题描述】:
我正在尝试导入一个图像文件,例如file.bmp,读取图像中每个像素的RGB值,然后输出每行RGB值最高的像素(最亮的像素) /em> 到屏幕上。关于如何使用 Python 来做这件事有什么建议吗?
【问题讨论】:
标签: python image image-processing rgb
我正在尝试导入一个图像文件,例如file.bmp,读取图像中每个像素的RGB值,然后输出每行RGB值最高的像素(最亮的像素) /em> 到屏幕上。关于如何使用 Python 来做这件事有什么建议吗?
【问题讨论】:
标签: python image image-processing rgb
您可以在这里充分利用 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
【讨论】:
axis 关键字。它非常有用。
好吧,您可以使用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 应该是 file_array。我已经更新了。