• Tetra Quark

Other Formats

  • PDF

Recoloring pixels with Python

Coding
Published

September 30, 2021

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}}\)

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.

An image I borrowed from a Seagate presentation by John Bent. It has white background, which doesn’t blend in with my blog’s background.

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
  imgName=   'posts/ligomodulation/PDH.png'
  img = Image.open(imgName)
  img = img.convert("RGBA")
  
  pixels = img.load()
  targetColor=[0,0,0]   # the original color
  replacementColor=[80,80,80]    # replacement color
  #replacementColor=(255,0,0)
  offsetSquared=100  # this is the sum of the squares of RGB values. Set this to 0 if you want the exact RGB value
  
  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:
           pixels[i, j] = replacementColor
  
  #img.show()
  imgNameS=imgName.split(".")
  img.save(imgNameS[0]+"_recolored."+imgNameS[1] )

Once the code is run, it changes the selected color.

The same image with the white background changed to (245,244,241).

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