我正在尝试导入图像文件,例如file.bmp,读取图像中每个像素的RGB值,然后输出每行的最高RGB值像素(最亮像素) < / em>到屏幕上。关于如何使用Python做任何建议?
答案 0 :(得分:1)
好吧,您可以使用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
答案 1 :(得分: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