0

I have set of 17 images and one of them has a highlighted pixel for my use. But, when I merge these 17 images, I get the color but it diffuses out of the pixel boundaries and I start seeing some colored pixel in black background.

I am using PIL library for the merging. I am attaching my code and the images for the reference. Any help would be appreciated.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Cretaing the Pixel array 

from PIL import Image
from PIL import ImageColor

img_path = '/Volumes/MY_PASSPORT/JRF/cancer_genome/gopal_gen/png_files/'

image_list = []
for entry in os.listdir(img_path):
    if entry.endswith('.png'):
        entry = int(entry.rstrip('.csv.png'))
        image_list.append(entry)
        image_list.sort()
list_img = []
for j in range(len(image_list)):
    stuff = str(image_list[j])+'.csv.png'
    list_img.append(stuff)
#print(list_img[0])

images = [Image.open(img_path+x) for x in list_img]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
    #print(total_width, max_height)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
    new_im.paste(im, (x_offset,0))
    #print(im.size)
    x_offset += im.size[0]
    #print(x_offset)
    new_im.save(img_path+'final_result_image.jpg')

Here is the combined image: The third column has a pixel highlighted.

enter image description here

Here is the zoomed in part with the problem.

enter image description here

1 Answers1

1

The JPEG format is lossy - it is allowed to change your pixels to make the file smaller. If your image is a conventional photo of a real-life scene, this doesn't normally matter. If your data is a blocky, computer-generated image, or a set of classes from a classification process, it can go horribly wrong if you use JPEG.

So, the answer is to use PNG (or potentially TIFF) format for images that need to be lossless.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • I have one more doubt. Say, if I have a fixed width of big image and I only want to keep pasting images in different columns (like pic above) till the max width is reached and then paste rest of the columns below in a second row. How can I do that? – Gopal Srivastava Nov 25 '20 at 05:57
  • Like image grid. – Gopal Srivastava Nov 25 '20 at 06:03
  • Never mind. Thanks. Anyone looking for image grid problem can refer to https://stackoverflow.com/questions/10647311/how-do-you-merge-images-into-a-canvas-using-pil-pillow and https://keestalkstech.com/2020/05/plotting-a-grid-of-pil-images-in-jupyter/ – Gopal Srivastava Nov 25 '20 at 06:27