Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

Python (or anything else vaguely sensible) - image conversion to monochrome.

Go to solution Solved by pythonmegapixel,

Using various responses from this thread and elsewhere, I've managed to cobble together a solution in Python using Pillow. I thought I'd just put my code here incase it helps anyone else:

from PIL import Image
import glob

for f in glob.glob("./png/*.png"):
	img = Image.open(f)
	pixels = img.load()
	size = img.size
	for w in range(size[0]):
		for h in range(size[1]):
			if pixels[w,h][3] > 0: # If the alpha channel is more than zero (i.e. is partially or fully transparent)
				pixels [w,h] = (0, 0, 0, 255) # Set to black, fully opaque
			else:
				pixels [w,h] = (0,0,0,0) # Set to fully transparent
	
	img.save(f + "_BLACK.png")

	

 

So here's the deal.

 

I have a folder full of loads of PNG graphics. Does anyone know of a Python library that would let me copy these files, but with every pixel that is not transparent set to black, and every pixel that is transparent remaining transparent?

 

I'm fairly familiar with python, and I'm also happy to use another language if needed, but if you want to link me to a library I'd prefer some pointers on what within the library I should be using (what functions/classes?) rather than just a link and nothing else... I'm not the most familiar with this kind of task.

Share your favourite custom styling rules (CSS) for websites! linustechtips.com/topic/1288887-share-your-favourite-custom-styling-rules-...

____________________________________________________________________________________________________________________________________

 

 

____________________________________________________________________________________________________________________________________

pythonmegapixel

into tech, public transport and architecture // amateur programmer // youtuber // beginner photographer

Thanks for reading all this by the way!

By the way, my desktop is a docked laptop. Get over it, No seriously, I have an exterrnal monitor, keyboard, mouse, headset, ethernet and cooling fans all connected. Using it feels no different to a desktop, it works for several hours if the power goes out, and disconnecting just a few cables gives me something I can take on the go. There's enough power for all games I play and it even copes with basic (and some not-so-basic) video editing. Give it a go - you might just love it.

Link to post
Share on other sites

If you don't mind Java, I could whip something up over lunch (like in a couple hours).

 

The pseudo-code gist:

  • Load in image
  • Iterate through each pixel, testing pixel 'A' channel value (how do you want to handle partial transparency?)
    • if 'A' is transparent, skip; else, if 'A' is not transparent, write black to pixel
  • Write out image

Main System (Byarlant): Ryzen 5 1600X | Asus B350-F Strix | Corsair H80i V2 | 16GB G.Skill DDR4 3200MHz CAS-14 | XFX RX 5600 XT THICC II | Samsung 960 PRO 512GB / Samsung 970 EVO 500GB / Seagate 7200RPM 3TB | Corsair CX650M | Mellanox ConnectX-2 10G NIC | Anidees AI-07BW Case | Dell U3415W Monitor | Microsoft Modern Keyboard

 

FreeNAS Server (Veda): Core i3-4170 | Supermicro X10SLL-F | Corsair H60 | 32GB Micron DDR3L ECC 1600MHz | 4x 10TB WD Whites / 1x Samsung PM961 128GB SSD / 1x Kingston 16GB SSD | Corsair CX430M | Mellanox ConnectX-2 10G NIC | LSI 9207-8i LBA | Fractal Design Node 804 Case (side panels swapped to show off drives)

 

Media Center/Video Capture (Jesta): Core i7-2600 | Asus H77M-PRO | Stock Cooler | 8GB No-name DDR3 | EVGA GTX750Ti SC | Sandisk UltraII SSD 64GB / Seagate 1.5TB HDD | Corsair CX450M | Hauppauge ImpactVCB-PCIe | Syba USB3.1 Gen 2 Card | LG UH12NS30 BD-ROM | Silverstone Sugo SG-11 Case

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB RAM (soldered) | Vega 6 Graphics | UMIS 256GB NVMe SSD | (all-around awesome machine)

Laptop (Rozen-ZuluSony VAIO VPCF13WFX | Core i7-740QM | 8GB Patriot DDR3 | GT 425M | Kingston 120GB SSD | Blu-ray Drive | (lived a good life, retired with honor)

 

Tablet (---): Samsung Galaxy Tab A 8" (crosses fingers)
Tablet (ReGZ)Asus T102HA (BIOS clock doesn't tick, loses time when sleep/off) (I kill tablets with disturbing regularity)

Tablet (Unicorn)Surface Pro 2 (battery will reset total capacity to current charge, leading Windows to think it's always 100% charged until it dies)

Tablet (Loto)Dell Venue 8 Pro (screen discoloration issues, wouldn't update to Windows 10)

Tablet: iPad 2 16GB (WiFi died, basically useless after that)

 

Testbed/Old Desktop (Kshatriya): Xeon X5470 @ 4.0GHz | ZALMAN CNPS9500 | Gigabyte EP45-UD3L | 8GB Nanya DDR2 400MHz | XFX HD6870 DD | OCZ Vertex 3 Max-IOPS 120GB | Corsair CX430M (?) | HooToo USB 3.0 PCIe Card | NZXT H230 Case

 

Camera: Sony ɑ7II (w/ Meike Grip) | Sony SEL24240 | Samyang 35mm ƒ/2.8 | Sony SEL50F18F | Sony SEL2870 (kit lens) | PNY Elite Perfomance SDXC cards

Link to post
Share on other sites
9 minutes ago, AbydosOne said:

If you don't mind Java, I could whip something up over lunch (like in a couple hours).

 

The pseudo-code gist:

  • Load in image
  • Iterate through each pixel, testing pixel 'A' channel value (how do you want to handle partial transparency?)
    • if 'A' is transparent, skip; else, if 'A' is not transparent, write black to pixel
  • Write out image

What you've described is indeed exactly what I need.

 

As for the handling of partial transparency... anything other than entirely transparent needs to be black. So essentially if the alpha-channel is anything less than 255, the pixel needs to be black.

 

I have no objection in principle to Java, but I don't have an environment for writing Java set up at the moment, so I would have to do that.

Share your favourite custom styling rules (CSS) for websites! linustechtips.com/topic/1288887-share-your-favourite-custom-styling-rules-...

____________________________________________________________________________________________________________________________________

 

 

____________________________________________________________________________________________________________________________________

pythonmegapixel

into tech, public transport and architecture // amateur programmer // youtuber // beginner photographer

Thanks for reading all this by the way!

By the way, my desktop is a docked laptop. Get over it, No seriously, I have an exterrnal monitor, keyboard, mouse, headset, ethernet and cooling fans all connected. Using it feels no different to a desktop, it works for several hours if the power goes out, and disconnecting just a few cables gives me something I can take on the go. There's enough power for all games I play and it even copes with basic (and some not-so-basic) video editing. Give it a go - you might just love it.

Link to post
Share on other sites
33 minutes ago, pythonmegapixel said:

What you've described is indeed exactly what I need.

 

As for the handling of partial transparency... anything other than entirely transparent needs to be black. So essentially if the alpha-channel is anything less than 255, the pixel needs to be black.

 

I have no objection in principle to Java, but I don't have an environment for writing Java set up at the moment, so I would have to do that.

You can use the pillow library to do this. 

 

from PIL import Image

im = Image.open('test.png')

for x in range(im.width):
    for y in range(im.height):
        r, g, b, transparency = im.getpixel((x,y))
        if transparency == 255:
            im.putpixel((x,y), (0, 0, 0, 255))

im = im.save('out.png')                        

 

Link to post
Share on other sites

Using various responses from this thread and elsewhere, I've managed to cobble together a solution in Python using Pillow. I thought I'd just put my code here incase it helps anyone else:

from PIL import Image
import glob

for f in glob.glob("./png/*.png"):
	img = Image.open(f)
	pixels = img.load()
	size = img.size
	for w in range(size[0]):
		for h in range(size[1]):
			if pixels[w,h][3] > 0: # If the alpha channel is more than zero (i.e. is partially or fully transparent)
				pixels [w,h] = (0, 0, 0, 255) # Set to black, fully opaque
			else:
				pixels [w,h] = (0,0,0,0) # Set to fully transparent
	
	img.save(f + "_BLACK.png")

	

 

Share your favourite custom styling rules (CSS) for websites! linustechtips.com/topic/1288887-share-your-favourite-custom-styling-rules-...

____________________________________________________________________________________________________________________________________

 

 

____________________________________________________________________________________________________________________________________

pythonmegapixel

into tech, public transport and architecture // amateur programmer // youtuber // beginner photographer

Thanks for reading all this by the way!

By the way, my desktop is a docked laptop. Get over it, No seriously, I have an exterrnal monitor, keyboard, mouse, headset, ethernet and cooling fans all connected. Using it feels no different to a desktop, it works for several hours if the power goes out, and disconnecting just a few cables gives me something I can take on the go. There's enough power for all games I play and it even copes with basic (and some not-so-basic) video editing. Give it a go - you might just love it.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×