Python 找到最小和最大像素的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21117415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
finding the value of the min and max pixel
提问by Mumfordwiz
I computed the smallest and largest pixel values for pixel in a grayscale image as follows:
我计算了灰度图像中像素的最小和最大像素值,如下所示:
smallest = numpy.amin(image)
biggest = numpy.amax(image)
but this will only works in grayscale.
但这仅适用于灰度。
How can I do the same for a color image (RGB)?
如何对彩色图像 (RGB) 执行相同操作?
回答by YXD
You can access each channel with the slices as follows:
您可以使用切片访问每个通道,如下所示:
# red
image[..., 0].min()
image[..., 0].max()
# green
image[..., 1].min()
image[..., 1].max()
# blue
image[..., 2].min()
image[..., 2].max()
回答by double_g
You can test it quickly in python script.
您可以在 python 脚本中快速测试它。
import numpy
img = numpy.zeros((10,10,3), dtype=numpy.int) # Black RGB image (10x10)
img[5,2] = [255, 255, 255]
print img.reshape((img.shape[0]*img.shape[1], 3)).max(axis=0)
array([255, 255, 255])
数组([255, 255, 255])
回答by Ratnajit Mukherjee
Assuming you have a BGR image (loaded using OpenCV), I found a simple way to do this:
假设你有一个 BGR 图像(使用 OpenCV 加载),我找到了一个简单的方法来做到这一点:
import numpy as np
max_channels = np.amax([np.amax(img[:,:,0]), np.amax(img[:,:,1]), np.amax(img[:,:,2])])
print(max_channels)
回答by Saad
import numpy
img = numpy.zeros((10,10,3), dtype=numpy.int)
img[5,2] = [255, 255, 255]
print img.reshape((img.shape[0]*img.shape[1], 3)).max(axis=0)
回答by Bill
If you want the results as arrays, this is a simple solution:
如果您希望结果为数组,这是一个简单的解决方案:
smallest = np.amin(image, axis=(0, 1))
largest = np.amax(image, axis=(0, 1))
But for some reason these are faster:
但出于某种原因,这些更快:
smallest = image.min(axis=0).min(axis=0)
biggest = image.max(axis=0).max(axis=0)
If you want the results as lists, just add .tolist()to the end of each above.
如果您希望将结果作为列表,只需添加.tolist()到上述每个的末尾。

