Recoloring pixels with Python
Coding
Abstract
I try to match the background color of my plots with the background color of the blog body. However, I sometimes need to borrow images from external sources, and they typically have white background. I don’t like the look of such images, see an example below. So, I ended up writing a quick Python code to change the background color, which can be copied below or can be cloned from my repository.
Keywords
Plotly, JavaScript
\(\require{cancel}\)
\(\require{cancel}\) \(\def\oot{\frac{1}{2}}\)
So, I ended up writing a quick Python code to change the background color, which can be copied below or can be cloned from my repository.
Code
# Replacing a target color in an image with another one
# 09/30/2021, tetraquark@gmail.com
# https://tetraquark.netlify.app/post/pythonRecolor/index.html
from PIL import Image
import math= 'posts/ligomodulation/PDH.png'
imgName= Image.open(imgName)
img = img.convert("RGBA")
img
= img.load()
pixels =[0,0,0] # the original color
targetColor=[80,80,80] # replacement color
replacementColor#replacementColor=(255,0,0)
=100 # this is the sum of the squares of RGB values. Set this to 0 if you want the exact RGB value
offsetSquared
for i in range(img.size[0]):
for j in range(img.size[1]):
if (pixels[i, j][0]-targetColor[0])**2 +(pixels[i, j][1]-targetColor[1])**2 +(pixels[i, j][2]-targetColor[1])**2 < offsetSquared and i>400:
= replacementColor
pixels[i, j]
#img.show()
=imgName.split(".")
imgNameSimg.save(imgNameS[0]+"_recolored."+imgNameS[1] )
Once the code is run, it changes the selected color.
If you have many such images, I have another version of the script that loops through the images in a selected folder. Find it in my repository.
No matching items