简体   繁体   English

如何在 python 中使用 PIL 读取图像的 HSV 值?

[英]How to read HSV values of an image using PIL in python?

I am trying to get the HSV values of all pixels in an image.我正在尝试获取图像中所有像素的 HSV 值。 I tested the below code with a plain magenta image and I got values which are much different from the values got from a converter online.我用普通洋红色图像测试了下面的代码,得到的值与从在线转换器获得的值有很大不同。 One more thing I realised is that none of the values of the resultant array are above 255 (Magenta has a H value of approx 300)我意识到的另一件事是结果数组的值都不高于 255(洋红色的 H 值约为 300)

`from PIL import Image

infile = 'magenta.jpg'
saturation = 0

img = Image.open(infile)
width, height = img.size
img_hsv = img.convert('HSV')

for x in range(width-1):
   for y in range(height-1):
      hsv = img_hsv.getpixel((x,y))
      print(hsv)`

Multiply the "R" value by 360/255, the "G" value by 100/255, and the "B" value by 100/255 to get the respective "H", "S", and "V" values.将“R”值乘以 360/255,将“G”值乘以 100/255,将“B”值乘以 100/255,得到相应的“H”、“S”和“V”值。 Also, when doing an actual image, I've found it easier and more efficient to use the method image.getdata(), instead of looping through every x and y value and using image.getpixel(xy):此外,在处理实际图像时,我发现使用 image.getdata() 方法比循环遍历每个 x 和 y 值并使用 image.getpixel(xy) 更容易、更有效:

from PIL import Image

infile = 'example.jpg'

img = Image.open(infile, 'r')
img_hsv = img.convert('HSV')
pixel_array = list(img_hsv.getdata())

hsv_pixel_array = []
for pixel in pixel_array:
    hsv_pixel_array.append(round((pixel[0]*(360/255), 1), round(pixel[1]*(100/255)), round(pixel[2]*(100/255))))

print(hsv_pixel_array)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM