Create a Personalized ‘I Love You’ Photo Mosaic with Python
This tutorial shows how to turn a loved one's photo into a heart‑shaped mosaic made of the phrase “I love you” using Python, OpenCV, and PIL by extracting pixel colors and drawing colored text onto a new image.
When Valentine's Day or Qixi approaches, many struggle to find a unique surprise for their partner. This guide presents a creative method: generate a photo where the shape of the image is formed by repeatedly writing the phrase “I love you”.
Requirements
Python 3.7 (or later)
OpenCV (cv2) – for reading the source image
Pillow (PIL) – for creating and drawing on a new image
Core Idea
Read an original picture, extract its pixel colors, and then create a blank canvas of the same size. By iterating over the canvas with a fixed step, write characters from the target phrase onto the canvas, coloring each character with the corresponding pixel’s RGB value. The result is a new image that visually resembles the original but is composed of the repeated phrase.
Implementation Steps
Import the required libraries.
import cv2
from PIL import Image, ImageDraw, ImageFontDefine a function that takes the source image path and the text to draw. def draw(pic, draw_text): Read the image and create a white canvas of identical dimensions.
img = cv2.imread(pic)
blank = Image.new("RGB", [img.shape[1], img.shape[0]], "white")
drawObj = ImageDraw.Draw(blank) # ready to draw textSet drawing parameters (these values work well for most photos):
n = 10 # pixel sampling interval
m = 9 # font size
font_path = "<your_font_path>"
font = ImageFont.truetype(font_path, size=m)Loop over the image pixels, placing characters and coloring them with the source pixel’s RGB values.
for i in range(0, img.shape[0], n):
for j in range(0, img.shape[1], n):
drawObj.text(
[j, i],
draw_text[int(j / n) % len(draw_text)],
fill=(img[i][j][2], img[i][j][1], img[i][j][0]),
font=font
)Save the generated image. blank.save('img_' + pic) Call the function with your photo and the desired phrase. draw('1.jpg', "我爱你") The final output is a unique, love‑themed picture that can be shared on social media or printed as a gift.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Huawei Cloud Developer Alliance
The Huawei Cloud Developer Alliance creates a tech sharing platform for developers and partners, gathering Huawei Cloud product knowledge, event updates, expert talks, and more. Together we continuously innovate to build the cloud foundation of an intelligent world.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
