Add a National Flag to Your Profile Picture Using Python and OpenCV
This tutorial shows how to use Python and the OpenCV library to programmatically overlay a national flag onto a profile picture, providing step‑by‑step code, scaling calculations, and instructions for saving the combined image.
Happy National Day! Instead of waiting for a platform to add a flag to your avatar, you can quickly create one yourself with Python and OpenCV.
Code example:
# -*- coding: utf8 -*-
import cv2
# 读取头像和国旗图案
img_head = cv2.imread('head.jpg')
img_flag = cv2.imread('flag.png')
# 获取头像和国旗图案宽度
w_head, h_head = img_head.shape[:2]
w_flag, h_flag = img_flag.shape[:2]
# 计算图案缩放比例
scale = w_head / w_flag / 4
# 缩放图案
img_flag = cv2.resize(img_flag, (0, 0), fx=scale, fy=scale)
# 获取缩放后新宽度
w_flag, h_flag = img_flag.shape[:2]
# 按3个通道合并图片
for c in range(0, 3):
img_head[w_head - w_flag:, h_head - h_flag:, c] = img_flag[:, :, c]
# 保存最终结果
cv2.imwrite('new_head.jpg', img_head)Save the script as a .py file, place your portrait image ( head.jpg) and the flag image ( flag.png) in the same directory, adjust the filenames if needed, and run the script with Python.
The resulting image will have the flag placed at the bottom‑right corner of the portrait, as shown in the example screenshots.
Implementation steps:
Read the portrait and flag images.
Calculate the scaling factor based on the portrait’s width so the flag occupies roughly one‑quarter of the width.
Resize the flag accordingly.
Replace the pixel values in the bottom‑right region of the portrait with the resized flag.
Save the combined image.
The script relies on the opencv-python package, which you need to install beforehand (e.g., pip install opencv-python).
For more on OpenCV and image processing, you can refer to the author’s previous articles:
Python Christmas Hat Tutorial
OpenCV‑Python: A Powerful Computer Vision Tool
Enjoy the holiday and celebrate the nation’s prosperity!
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.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
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.
