How to create a region containing all non-transparent area of an image?

Hi there,

I want to create a region out on an image so that the region contains every pixel that is not completely transparent.
My input image might be either SVG or PNG, but as I know the target size and can create a wx.Bitmap from an SVG the difference doesn’t really matter.

My issue is that the wx.Region(wx.Bitmap) constructor just creates a square Region that the image fits in, while the wx.Region(wx.Bitmap, wx.Colour) constructor doesn’t care about transparency:

region = wx.Region(image, wx.Colour(0, 0, 0, wx.ALPHA_TRANSPARENT))

This will create a region where all transparent areas are not included in the region, but all fully opaque black areas as well.

As the image is user-provided I can’t just delegate one colour for turning into transparency and even less provide a matching monochrome bitmap I could just use.

One other approach I investigated was modifying the image by recolouring all non-transparent pixels (alpha != 0) to white, but I don’t see how I can do that efficiently, the only viable option I saw was exporting the binary with wx.Bitmap.CopyToBuffer() then modifying it on bit level and finally reimporting it with wx.Bitmap.CopyFromBuffer().

At this point I thought that there should be an easier way but to implement an “colour opaque-to-white, transparent-to-black” method myself. So, you got any ideas / tips?


EDIT: git repository with my test code and assets: GitHub - seyfahni/desky

Well, when I do pictures proper I use GIMP and proper tone mappers; but what about Pillow (I use it only for thumbnails etc): they are talking about a bitmap as ‘transparency mask’ or ‘matte’; I wouldn’t expect transparency near Python since the three standard channels of a single! layer already make it look very, very old :hot_face: