简体   繁体   中英

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. 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)

`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. 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):

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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