Created
December 28, 2023 09:34
-
-
Save JupyterJones/28d4d6236e0a651e3c1a630244b42283 to your computer and use it in GitHub Desktop.
convert any image to a specified rgb array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image, ImageFilter | |
import os | |
import cv2 | |
import random | |
import time | |
path = r"/home/jack/Desktop/HDD500/SCRIPTS/UGLY_DOLLS/" | |
#path = r"crawler4/" | |
base_image = random.choice([ | |
x for x in os.listdir(path) | |
if os.path.isfile(os.path.join(path, x)) | |
]) | |
filename0=(path+base_image) | |
filename0="/home/jack/Desktop/HDD500/www/newlongest.jpg" | |
im = Image.open(filename0) | |
imP = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=6) | |
imP.putpalette([ | |
255,255,0, | |
255,0,0, | |
0,255,255, | |
0,0,255, | |
0,0,0, | |
255,255,255, | |
]) | |
im2 = Image.open(filename0) | |
mask0 = im2.convert('L') # need a greyscale image to create a mask | |
mask = Image.eval(mask0, lambda a: 255 if a == 0 else 0) | |
mask = mask.filter(ImageFilter.MinFilter(3)) | |
imP.paste(2, mask) # Paste the color of index 2 using image2 as a mask | |
filename = time.strftime("junk/PILStuff%Y%m%d%H%M%S.png") | |
imP.save(filename) | |
print (filename) | |
imP |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script performs the following operations using the Python Imaging Library (PIL), now known as the Pillow library:
base_image = random.choice([
x for x in os.listdir(path)
if os.path.isfile(os.path.join(path, x))
])
Converting the Image to a Palette Mode:
python
imP = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=6)
Defining a Custom Palette:
python
imP.putpalette([
255,255,0,
255,0,0,
0,255,255,
0,0,255,
0,0,0,
255,255,255,
])
Creating a Mask:
python
mask0 = im2.convert('L') # Grayscale image
mask = Image.eval(mask0, lambda a: 255 if a == 0 else 0)
mask = mask.filter(ImageFilter.MinFilter(3))
Applying the Mask to the Palette Image:
python
imP.paste(2, mask)
Saving the Resulting Image:
python
filename = time.strftime("junk/PILStuff%Y%m%d%H%M%S.png")
imP.save(filename)
Print and Display:
python
In summary, the script takes a random image, converts it to palette mode, defines a custom palette, creates a mask, and then applies the mask to the palette image, resulting in a modified image that is saved with a timestamped filename.