本文来源公众号“小白学视觉”,仅用于学术分享,侵权删,干货满满。
使用 CV2 在 Python 中以编程方式完成如下操作:将非方形图像转换为方形图像。

因此,6 年来,我第一次将一些图片上传到 Instagram。我画了一些愚蠢的漫画,想上传它来娱乐一下。然而,问题:
-
我有 10 张图片要上传
-
每个图像都有不同的尺寸
-
Instagram 会自动将你的图像 (ew) 裁剪为:
-
方形
-
4:5 纵横比
-
9:16 纵横比
-
所以我需要一种方法来为我的图像添加白色填充,使它们都是正方形。
以下是我如何使用 Python 实现的:
文件夹结构
- myimages
- 1.png
- 2.png
- 3.png
- 4.png
- 5.png
- 6.png
run.py
安装依赖
pip install opencv-python
完整代码
# run.py
import cv2
import os
# replace this with your own folder name
# your folder should contain all images you want to squarify
folder = 'yourfolder'
new_folder = f'{folder}_new'
if not os.path.exists(new_folder):
os.mkdir(new_folder)
for filename in os.listdir(folder):
if '.png' not in filename.lower():
continue
filepath = f'{folder}/{filename}'
img = cv2.imread(filepath)
h, w = img.shape[:2]
px, py = 0, 0
if h > w:
px = (h-w)//2
elif h < w:
py = (w-h)//2
newimg = cv2.copyMakeBorder(
img, py, py, px, px, borderType=cv2.BORDER_CONSTANT, value=[255,255,255]
)
cv2.imwrite(f'{new_folder}/{filename}', newimg)
代码中发生了什么
import cv2
import os
# replace this with your own folder name
# your folder should contain all images you want to squarify
folder = 'myimages'
# name of folder the NEW images will be in
new_folder = f'{folder}_new'
# if this folder doesn't exist, create it
if not os.path.exists(new_folder):
os.mkdir(new_folder)
# looping through all images in our folder
for filename in os.listdir(folder):
# ignoring anything that isn't an image
# rememeber to change this is you're using jpg or something else
if '.png' not in filename.lower():
continue
filepath = f'{folder}/{filename}'
# reading the image using cv2.imread
# img is a numpy 3d array
img = cv2.imread(filepath)
# extracting height/width of image
h, w = img.shape[:2]
# px --> number of padding pixels to add on left/right
# py --> number of padding pixels to add on top/bottom
px, py = 0, 0
# checking if image height is more than image width
if h > w:
# calculating pixels to add to left/right
# py will be 0
px = (h-w)//2
elif h < w:
# calculating pixels to add to top/bottom
# py will be 0
py = (w-h)//2
# creating new image with padding
newimg = cv2.copyMakeBorder(
img, py, py, px, px,
borderType=cv2.BORDER_CONSTANT,
value=[255,255,255] # white (change this if you want other colors)
)
# saving our image
cv2.imwrite(f'{new_folder}/{filename}', newimg)
运行后的结果文件夹结构
- myimages
- 1.png
- 2.png
- 3.png
- 4.png
- 5.png
- 6.png
- myimages_new
- 1.png
- 2.png
- 3.png
- 4.png
- 5.png
- 6.png
run.py
运行我们的 Python 脚本后,该myimages_new文件夹会自动生成。对于myimages中的每张图片,都会在myimages_new 中生成对应的同名正方形图片。
THE END !
文章结束,感谢阅读。您的点赞,收藏,评论是我继续更新的动力。大家有推荐的公众号可以评论区留言,共同学习,一起进步。

203

被折叠的 条评论
为什么被折叠?



