且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

寻找图像中最大值的坐标

更新时间:2023-02-04 09:01:20

有一个 getextrema()方法返回每个频段使用的最低和最高图像数据。因此,为了找到最亮的像素,您需要首先获得图像的灰度副本。然后,您可以迭代图像中的每个像素,并检查每个像素是否具有最高灰度值:

There is a getextrema() method that returns the lowest and highest image data used for every band. So in order to find the brightest pixels, you need a grayscale copy of your image first. Then you can iterate over every pixel in the image and check each pixel whether it has the highest grayscale value:

grayscale = image.convert('L')
minima, maxima = grayscale.getextrema()

for width in image.size[0]:
   for height in image.size[1]:
       if grayscale.getpixel((width, height)) == maxima:
            # So here we have one pixel with the highest brightness.

然而,根据您实际尝试实现的目标,可能会有更简单,更有效的方法。例如,当您想要在黑色背景上粘贴所有最亮的像素时,您可以这样做:

However dependent on what you are actually try to achieve there might be simpler and more efficient ways of doing it. For example when you want to paste all the brightest pixels on a black background, you could do it like that:

grayscale = image.convert('L')
minima, maxima = grayscale.getextrema()
mask = image.point([0] * maxima + [255] * (256 - maxima))

new_image = PIL.Image.new('RGB', image.size)
new_image.paste(image, mask=mask)