1

I have been having trouble trying to save a png image with sRGB and an alpha channel. I first crop an image and then save it like this:

from PIL import Image
import cv2

inputPath = 'picture.png'
img = cv2.imread(inputPath)

crop_img = img[bounds[3]:bounds[2], bounds[1]:bounds[0]]
pth = name + ".png"
crop_img.save(pth)

This however creates a file like this:

I want the file to be like this though:

How can I get this result in python?

P.S. The original image does have an alpha channel and sRGB colour profile.

Any help is greatly appreciated!

J.Treutlein
  • 963
  • 8
  • 23
  • please share sample images to illustrate the problem – Saransh Kejriwal Apr 25 '18 at 05:32
  • 3
    you are only cropping the image... where do you add the alpha channel? or you mean the alpha channel comes with the image? then use the `cv2.IMREAD_UNCHANGED` flag when reading – api55 Apr 25 '18 at 05:33

1 Answers1

3

You can read your image as follows. It will load your image as such including the alpha channel.

img = cv2.imread(inputPath,-1)

UPDATE

Following code is equivalent to the above given answer since cv2.IMREAD_UNCHANGED=-1 in documentation. Though above snippet solve the issue, it is not a good programming practice to use it since it doesn't give the idea about what is really -1 does. But following code snippet gives an explicit idea about the behavior of the code.

img = cv2.imread(input,cv2.IMREAD_UNCHANGED)
Ishara Madhawa
  • 3,549
  • 5
  • 24
  • 42
  • Thanks for the reply but @api55's comment worked, I'll add it as an answer now – J.Treutlein Apr 25 '18 at 06:01
  • 1
    Yes, that comment says the same thing in another words. – Ishara Madhawa Apr 25 '18 at 06:04
  • 3
    It is highly recommended not to use "magic numbers", but the constant value variable. This way, if it changes in the future it will still work and it is easier to understand the code afterwards :) – api55 Apr 25 '18 at 08:51
  • Downvoting, since you're basically suggesting to use magic numbers instead of named constants. – Dan Mašek Apr 25 '18 at 10:35
  • OK, but I'd suggest to completely remove that first snippet (or explicitly explain why that's not a good practice ;) -- comments can disappear and you can bet that in many cases they won't be read). – Dan Mašek Apr 25 '18 at 13:37