算法描述:
import cv2 as cv
import os
import numpy as np
path_image = ""
save_path = ""
def sava_image(source_path, dest_path, q):
img = cv.imread(source_path)
cv.imwrite(dest_path, img, [int(cv.IMWRITE_JPEG_QUALITY), q])
# 功能:等比例缩放图像大小,如果比例不对则剪裁成对应的比例
def resize_image(image_path_, path_save_, size, q_, index_):
img = cv.imread(image_path_)
try:
height, width, channel = img.shape
if width > height: # 宽图
new_width = int(width/(height/size[1]))
img = cv.resize(img, (new_width, size[1]))
print(new_width, size[1])
start_point = int((new_width - size[0])/2)
img = img[0:size[1], start_point:start_point+size[0]]
elif width < height: # 高图
new_height = int(height*size[0]/width)
img = cv.resize(img, (size[0], new_height))
start_point = int((new_height - size[1]) / 2)
img = img[start_point:start_point + size[1], 0:size[0]]
elif width == height: # 方图
if size[0] > size[1]: # 如果被减的是个宽图,那么按这个宽度进行缩放
pass # TODO 暂不处理
try:
text = "{}*{} q={}".format(size[0], size[1], q_)
img = img.copy()
cv.putText(img, text, (10, 50), cv.FONT_HERSHEY_COMPLEX, 1.0, (255, 200, 200), 2)
# 将原图片和添加文字后的图片拼接起来
# img = np.hstack([img, add_text])
cv.imwrite(os.path.join(path_save_, "{}_{}_{}_{}.jpg".format(size[0], size[1], q_, index_)), img, [int(cv.IMWRITE_JPEG_QUALITY), q_])
except Exception as e:
print(e)
except Exception as e:
print(image_path_, "出错")
if __name__ == '__main__':
image_file_path = r"C:\Users\Administrator\Desktop\images"
path_save = r"C:\Users\Administrator\Desktop\images\save"
list_image_path = [os.path.join(image_file_path, filename) for filename in os.listdir(image_file_path)]
list_q = [50, 60, 65, 70, 75]
list_size = [(1024, 768), (768, 768), (512, 512), (256, 256)]
for index, image_path in enumerate(list_image_path):
for q in list_q:
for size in list_size:
resize_image(image_path, path_save, size, q, index + 1)
本文介绍了一个使用Python实现的图像处理脚本,通过resize_image函数,实现等比例缩放图像并添加质量标识,适用于不同尺寸和JPEG压缩等级。着重于图像调整与文件操作,适合前端与后端开发者学习图像处理技术。
763

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



