7

I currently read off pixels from an image using python PIL. These pixels are 16bit greyscale and are unsigned. However, whenever PIL reads them in it thinks they are signed and makes values that should be something like 45179 into -20357.

org_Image = Image.open(image)
org_Data = org_Image.load()
width, height = org_Image.size

    for y in range(0, height):
        temprow_data = []
        for x in range(0, width):
             temprow_data.append(org_Data[x, y])

How do I go about getting PIL to output unsigned instead of signed integers? Or is there a really easy way of taking the PIL input and converting it after?

2 Answers 2

8

Here is a solution with structs since I do not know how python represents negative numbers binarily.

import struct
struct.unpack('H', struct.pack('h', number))

It packs it as a short (2 bytes) and unpacks it as an unsigned short.

Sign up to request clarification or add additional context in comments.

2 Comments

good answer :) and maybe less of a sledgehammer than mine (you know something about when you have a hammer everything looks like a nail)
you may want to mention this returns a tuple (number,)
3
>>> import numpy as np
>>> np.array([-20357],dtype="uint16")
array([45179], dtype=uint16)

in your case when you are done looping over everything and you have it in a list

just call np.array(my_list,dtype="uint16")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.