Embedding Hidden Text in an Image Using Python (cv2 & PIL)
This tutorial demonstrates how to use Python's OpenCV and Pillow libraries to read a photo, create a white canvas, and embed hidden text into image blocks so that the message is invisible at normal view but appears when zoomed in, with adjustable font and spacing parameters.
The article explains a fun Python project where a programmer embeds a secret message into a photograph using image processing techniques, making the text invisible at normal size but visible when the image is enlarged.
The approach involves reading the original image with cv2.imread , creating a same‑size white image using PIL.Image.new , and then iterating over the image in blocks to draw characters from a supplied string onto the new canvas, using the pixel colors from the original image as the text color.
Below is the complete Python script (ensure the font file path is correct and adjust the block size n and font size m as desired): # -*- coding:utf-8 -*- from PIL import Image, ImageDraw, ImageFont import cv2 font_path = './font-family/MiNiJianPangWa-1.ttf' def draw(image_path, draw_text): img = cv2.imread(image_path) # read image file img_temp = Image.new("RGB", [img.shape[1], img.shape[0]], "white") # create white canvas drawObj = ImageDraw.Draw(img_temp) n = 8 # block interval m = 8 # font size font = ImageFont.truetype(font_path, size=m) 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) img_temp.save('img_' + image_path) draw('bingbing.jpg', "都是冰冰的") # you can modify the text
Users should replace font_path with a valid TrueType font file; the author found a particular font that yields good visual results. Both the block size n and font size m can be tuned, though a value of 8 for each generally provides a clear hidden message.
After running the script, the generated image (shown in the original article) appears normal on a phone, but when zoomed in the hidden characters become visible. If the enlarged image looks blurry, an online lossless upscaling tool can be used to enhance clarity.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.