我正在尝试导入一个图像文件,例如 file.bmp,读取图像中每个像素的 RGB 值,然后将每行的最高 RGB 值像素(最亮的像素)输出到屏幕。关于如何使用 Python 执行此操作的任何建议?
问问题
1233 次
2 回答
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
于 2013-03-28T00:59:29.660 回答
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
于 2013-03-28T02:02:59.633 回答