Last active
April 15, 2021 12:39
-
-
Save robinvanyang/0755fc191c675696eb870dea187c2387 to your computer and use it in GitHub Desktop.
头像图片缩放
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# 注意: 需手动新建result文件夹 | |
import os | |
from shutil import copyfile | |
import cv2 | |
base = './images/' | |
destination = "./result/" | |
max_width = 500 | |
max_height = 500 | |
def scale_image(image_name): | |
image_path = base + image_name | |
img = cv2.imread(image_path) | |
height, width = img.shape[:2] | |
print("original: %d/%d" % (width, height)) | |
if width < max_width and height < max_height: | |
print("不需要裁剪: %d/%d" % (width, height)) | |
# 不需要进行裁剪,直接copy到目标文件夹 | |
copyfile(image_path, destination + image_name) | |
else: | |
width_ratio = width / max_width | |
height_ratio = height / max_height | |
real_ratio = max(width_ratio, height_ratio) | |
print("裁剪尺寸: %f/%f" % (width / real_ratio, height / real_ratio)) | |
real_width = round(width / real_ratio) | |
real_height = round(height / real_ratio) | |
result = cv2.resize(img, (real_width, real_height), interpolation=cv2.INTER_CUBIC) | |
cv2.imwrite(destination + image_name, result) | |
def iterate_all_image(folder): | |
for root, ds, fs in os.walk(folder): | |
for f in fs: | |
yield f | |
def main(): | |
for name in iterate_all_image(base): | |
scale_image(name) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment