Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python String Exercise
Next article icon

Implementing Photomosaics

Last Updated : 27 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Introduction

A photomosaic is an image split into a grid of rectangles, with each replaced by another image that matches the target (the image you ultimately want to appear in the photomosaic). In other words, if you look at a photomosaic from a distance, you see the target image; but if you come closer, you will see that the image actually consists of many smaller images. This works because of how the human eye works.

There are two kinds of mosaic, depending on how the matching is done. In simpler kind, each part of the target image is averaged down to a single color. Each of the library images is also reduced to a single color. Each part of the target image is then replaced with one from the library where these colors are as similar as possible. In effect, the target image is reduced in resolution (by downsampling), and then each of the resulting pixels is replaced with an image whose average color matches that pixel.

In the more advanced kind of photographic mosaic, the target image is not downsampled, and the matching is done by comparing each pixel in the rectangle to the corresponding pixel from each library image. The rectangle in the target is then replaced with the library image that minimizes the total difference. This requires much more computation than the simple kind, but the results can be much better since the pixel-by-pixel matching can preserve the resolution of the target image.

How to create Photomosaics? 

  1. Read the tile images, which will replace the tiles in the original image.
  2. Read the target image and split it into an M×N grid of tiles.
  3. For each tile, find the best match from the input images.
  4. Create the final mosaic by arranging the selected input images in an M×N grid.


Splitting the images into tiles


Now let’s look at how to calculate the coordinates for a single tile from this grid. The tile with index (i, j) has a top-left corner coordinate of (i*w, i*j) and a bottom-right corner coordinate of ((i+1)*w, (j+1)*h), where w and h stand for the width and height of a tile, respectively. These can be used with the PIL to crop and create a tile from this image.
Averaging Color Values
Every pixel in an image has a color that can be represented by its red, green, and blue values. In this case, you are using 8-bit images, so each of these components has an 8-bit value in the range [0, 255]. Given an image with a total of N pixels, the average RGB is calculated as follows:
\left ( r,g,b \right )_{avg}=\left ( \frac{\left ( r_{1} + r_{2} +....+ r_{N} \right )}{N}, \frac{\left ( g_{1} + g_{2} +....+ g_{N} \right )}{N}, \frac{\left ( b_{1} + b_{2} +....+ b_{N} \right )}{N} \right )
Matching Images
For each tile in the target image, you need to find a matching image from the images in the input folder specified by the user. To determine whether two images match, use the average RGB values. The closest match is the image with the closest average RGB value. 
The simplest way to do this is to calculate the distance between the RGB values in a pixel to find the best match among the input images. You can use the following distance calculation for 3D points from geometry:
D_{1, 2}=\sqrt{\left ( r_{1} - r_{2} \right )^{2} + \left ( g_{1} - g_{2} \right )^{2} + \left ( b_{1} - b_{2} \right )^{2}}
Now lets try to code this out

Python3

#Importing the required libraries
import os, random, argparse
from PIL import Image
import imghdr
import numpy as np
 
def getAverageRGBOld(image):
  """
  Given PIL Image, return average value of color as (r, g, b)
  """
  # no. of pixels in image
  npixels = image.size[0]*image.size[1]
  # get colors as [(cnt1, (r1, g1, b1)), ...]
  cols = image.getcolors(npixels)
  # get [(c1*r1, c1*g1, c1*g2),...]
  sumRGB = [(x[0]*x[1][0], x[0]*x[1][1], x[0]*x[1][2]) for x in cols]
  # calculate (sum(ci*ri)/np, sum(ci*gi)/np, sum(ci*bi)/np)
  # the zip gives us [(c1*r1, c2*r2, ..), (c1*g1, c1*g2,...)...]
  avg = tuple([int(sum(x)/npixels) for x in zip(*sumRGB)])
  return avg
 
def getAverageRGB(image):
  """
  Given PIL Image, return average value of color as (r, g, b)
  """
  # get image as numpy array
  im = np.array(image)
  # get shape
  w,h,d = im.shape
  # get average
  return tuple(np.average(im.reshape(w*h, d), axis=0))
 
def splitImage(image, size):
  """
  Given Image and dims (rows, cols) returns an m*n list of Images
  """
  W, H = image.size[0], image.size[1]
  m, n = size
  w, h = int(W/n), int(H/m)
  # image list
  imgs = []
  # generate list of dimensions
  for j in range(m):
    for i in range(n):
      # append cropped image
      imgs.append(image.crop((i*w, j*h, (i+1)*w, (j+1)*h)))
  return imgs
 
def getImages(imageDir):
  """
  given a directory of images, return a list of Images
  """
  files = os.listdir(imageDir)
  images = []
  for file in files:
    filePath = os.path.abspath(os.path.join(imageDir, file))
    try:
      # explicit load so we don't run into resource crunch
      fp = open(filePath, "rb")
      im = Image.open(fp)
      images.append(im)
      # force loading image data from file
      im.load()
      # close the file
      fp.close()
    except:
      # skip
      print("Invalid image: %s" % (filePath,))
  return images
 
def getImageFilenames(imageDir):
  """
  given a directory of images, return a list of Image file names
  """
  files = os.listdir(imageDir)
  filenames = []
  for file in files:
    filePath = os.path.abspath(os.path.join(imageDir, file))
    try:
      imgType = imghdr.what(filePath)
      if imgType:
        filenames.append(filePath)
    except:
      # skip
      print("Invalid image: %s" % (filePath,))
  return filenames
 
def getBestMatchIndex(input_avg, avgs):
  """
  return index of best Image match based on RGB value distance
  """
 
  # input image average
  avg = input_avg
   
  # get the closest RGB value to input, based on x/y/z distance
  index = 0
  min_index = 0
  min_dist = float("inf")
  for val in avgs:
    dist = ((val[0] - avg[0])*(val[0] - avg[0]) +
            (val[1] - avg[1])*(val[1] - avg[1]) +
            (val[2] - avg[2])*(val[2] - avg[2]))
    if dist < min_dist:
      min_dist = dist
      min_index = index
    index += 1
 
  return min_index
 
 
def createImageGrid(images, dims):
  """
  Given a list of images and a grid size (m, n), create
  a grid of images.
  """
  m, n = dims
 
  # sanity check
  assert m*n == len(images)
 
  # get max height and width of images
  # ie, not assuming they are all equal
  width = max([img.size[0] for img in images])
  height = max([img.size[1] for img in images])
 
  # create output image
  grid_img = Image.new('RGB', (n*width, m*height))
   
  # paste images
  for index in range(len(images)):
    row = int(index/n)
    col = index - n*row
    grid_img.paste(images[index], (col*width, row*height))
     
  return grid_img
 
 
def createPhotomosaic(target_image, input_images, grid_size,
                      reuse_images=True):
  """
  Creates photomosaic given target and input images.
  """
 
  print('splitting input image...')
  # split target image
  target_images = splitImage(target_image, grid_size)
 
  print('finding image matches...')
  # for each target image, pick one from input
  output_images = []
  # for user feedback
  count = 0
  batch_size = int(len(target_images)/10)
 
  # calculate input image averages
  avgs = []
  for img in input_images:
    avgs.append(getAverageRGB(img))
 
  for img in target_images:
    # target sub-image average
    avg = getAverageRGB(img)
    # find match index
    match_index = getBestMatchIndex(avg, avgs)
    output_images.append(input_images[match_index])
    # user feedback
    if count > 0 and batch_size > 10 and count % batch_size is 0:
      print('processed %d of %d...' %(count, len(target_images)))
    count += 1
    # remove selected image from input if flag set
    if not reuse_images:
      input_images.remove(match)
 
  print('creating mosaic...')
  # draw mosaic to image
  mosaic_image = createImageGrid(output_images, grid_size)
 
  # return mosaic
  return mosaic_image
 
# Gather our code in a main() function
def main():
  # Command line args are in sys.argv[1], sys.argv[2] ..
  # sys.argv[0] is the script name itself and can be ignored
 
  # parse arguments
  parser = argparse.ArgumentParser
    (description='Creates a photomosaic from input images')
  # add arguments
  parser.add_argument('--target-image', dest='target_image', required=True)
  parser.add_argument('--input-folder', dest='input_folder', required=True)
  parser.add_argument('--grid-size', nargs=2, dest='grid_size', required=True)
  parser.add_argument('--output-file', dest='outfile', required=False)
 
  args = parser.parse_args()
 
  ###### INPUTS ######
 
  # target image
  target_image = Image.open(args.target_image)
 
  # input images
  print('reading input folder...')
  input_images = getImages(args.input_folder)
 
  # check if any valid input images found 
  if input_images == []:
      print('No input images found in %s. Exiting.' % (args.input_folder, ))
      exit()
 
  # shuffle list - to get a more varied output?
  random.shuffle(input_images)
 
  # size of grid
  grid_size = (int(args.grid_size[0]), int(args.grid_size[1]))
 
  # output
  output_filename = 'mosaic.png'
  if args.outfile:
    output_filename = args.outfile
   
  # re-use any image in input
  reuse_images = True
 
  # resize the input to fit original image size?
  resize_input = True
 
  ##### END INPUTS #####
 
  print('starting photomosaic creation...')
   
  # if images can't be reused, ensure m*n <= num_of_images
  if not reuse_images:
    if grid_size[0]*grid_size[1] > len(input_images):
      print('grid size less than number of images')
      exit()
   
  # resizing input
  if resize_input:
    print('resizing images...')
    # for given grid size, compute max dims w,h of tiles
    dims = (int(target_image.size[0]/grid_size[1]),
            int(target_image.size[1]/grid_size[0]))
    print("max tile dims: %s" % (dims,))
    # resize
    for img in input_images:
      img.thumbnail(dims)
 
  # create photomosaic
  mosaic_image = createPhotomosaic(target_image, input_images, grid_size,
                                   reuse_images)
 
  # write out mosaic
  mosaic_image.save(output_filename, 'PNG')
 
  print("saved output to %s" % (output_filename,))
  print('done.')
 
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
  main()
                      
                       
python test.py --target-image test-data/a.jpg --input-folder test-data/set1/ --grid-size 128 128

Output:

https://media.geeksforgeeks.org/wp-content/uploads/2017-11-06-at-01-47-50.mp4


Reference Links:
1) Python Playground by Mahesh Venkitachalam. 
2) PILLOW docs 
3) Wikipedia – Photomosaics



Next Article
Python String Exercise
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Project
  • Python
  • Technical Scripter
Practice Tags :
  • python

Similar Reads

  • Complexity Metrics
    The productivity, if measured only in terms of lines of code per unit of time, can vary a lot depending on the complexity of the system to be developed. A programmer will produce a lesser amount of code for highly complex system programs, as compared to a simple application program. Similarly, compl
    7 min read
  • Incremental Programming in Python
    In incremental systems, every measurement refers to a previously dimensioned position (point-to-point). Incremental dimensions are the distances between two adjacent points. An incremental movement moves A distance based on your current position. Start Small - First of all, start your program small
    2 min read
  • Mathematics Tricks For Competitive Programming In Python 3
    Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is
    3 min read
  • Compiler Design - Science of Building a Compilers
    The purpose of this article is to provide an introduction to the science of compiler design, by describing how code generation and optimization work, as well as modeling in compiler design and implementation. Below, these topics are important to understand before building a compiler. Code Generation
    8 min read
  • Python String Exercise
    Basic String ProgramsCheck whether the string is Symmetrical or PalindromeFind length of StringReverse words in a given StringRemove i’th character from stringAvoid Spaces in string lengthPrint even length words in a stringUppercase Half StringCapitalize the first and last character of each word in
    4 min read
  • Python – The new generation Language
    INTRODUCTION: Python is a widely-used, high-level programming language known for its simplicity, readability, and versatility. It is often used in scientific computing, data analysis, artificial intelligence, and web development, among other fields. Python's popularity has been growing rapidly in re
    6 min read
  • Introduction to Simulation Modeling in Python
    Simulation is imitating the operations which take place within a system to study its behavior. Analyzing and creating the model of a system to predict its performance is called simulation modeling. Simulation mimics a real-life process to determine or predict the response of the entire system. This
    4 min read
  • Which Python Modules are useful for competitive programming?
    In the previous article, we have discussed that C++, Java and Python are three most common languages for competitive programming. In this article, we are going to focus on the most important Python modules from competitive programming and interview preparation point of view. list : Dynamic Sized Arr
    3 min read
  • Python OOPs Coding Practice Problems
    Object-Oriented Programming (OOP) is a fundamental concept in Python that helps structure code for better readability and reusability. This collection of Python OOPs coding practice problems covers everything from defining classes and objects to solving advanced challenges like implementing design p
    2 min read
  • OpenMP | Introduction with Installation Guide
    After a long thirst for parallelizing highly regular loops in matrix-oriented numerical programming, OpenMP was introduced by OpenMP Architecture Review Board (ARB) on 1997 . In the subsequent releases, the enthusiastic OpenMP team added many features to it including the task parallelizing, support
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences