Reputation: 93
I want to crop an image and save it, but the problem is that the image changes hue significantly after saving the same format. Why is this happening? I'm not even converting it in the process.
Here is my code:
def square_crop(resized_image):
print "square crop"
width, height = resized_image.size
print width,height
edge_length = 3600
if(width >= height):
print("width>=height")
left = (width - edge_length)/2
top = (height - edge_length)/2
right = (width + edge_length)/2
bottom = (height + edge_length)/2
squared_image = resized_image.crop((left, top, right, bottom))
squared_image.save('squared.png')
And the confusing part is that this code uses the same image and saves it without hue change, so the cropping function must have an issue:
def image_resize(image):
print "image resize"
width, height = image.size
print width,height
if(width > 3601 and height > 3601):
print width, height
if(width >= height):
ratio = float(width)/float(height)
w = 3601 * ratio
h = 3601.0
print ratio, w, h
resized_image = image.resize([int(w), int(h)])
resized_image.save("resized.png")
else:
ratio = float(height)/float(width)
print(ratio)
w = 3601.0
h = 3601 * ratio
print ratio, w, h
resized_image = image.resize([int(w), int(h)])
resized_image.save("heic1509a_resized.png")
*EDIT: When I import .jpg file and save to .jpg both functions have the same hue issue. Same with .tif.
**EDIT: Also I've noticed that for some images this red color loss does not happen. I truly don't have any idea what is going on. I will leave the before and after screenshots to see for yourself.
***EDIT: The problem is from the color space as the images that have changed color when saved were encoded using ProPhoto RGB color space(ROMM RGB (Reference Output Medium Metric)).
I am using gimp2 to convert them first to RGB without losing color, but I would want to find a way to do that automatically from python.
I will post any new updates on this issue.
Upvotes: 0
Views: 410
Reputation: 93
The problem was that when I was saving the file, the PIL library automatically switched the color space of the image(ROMM-RGB) to other color space(RGB or sRGB) and basically every color changed.
All you have to do is preserve the color space of the image and you're fine. If you want to convert to another color space you should look up OpenCV library.
I can't explain too much in detail because I am just breaking the ice on this. Here is the code that solved this issue:
resized_image.save('resized.jpg', #file name
format = 'JPEG', #format of the file
quality = 100, #compression quality
icc_profile = resized_image.info.get('icc_profile','')) #preserve the icc profile of the photo(this was the one that caused problems)
Here is a link to a more in-depth answer: LINK
Upvotes: 1