短视频软件开发,比例缩放图片不变形
短视频软件开发,比例缩放图片不变形实现的相关代码
```handlebars import cv2 import numpy as np def resizeAndPad(img, size, padColor=0): h, w = img.shape[:2] sh, sw = size # interpolation method if h > sh or w > sw: # shrinking image interp = cv2.INTER_AREA else: # stretching image interp = cv2.INTER_CUBIC # aspect ratio of image aspect = w / h # if on Python 2, you might need to cast as a float: float(w)/h # compute scaling and pad sizing if aspect > 1: # horizontal image new_w = sw new_h = np.round(new_w / aspect).astype(int) pad_vert = (sh - new_h) / 2 pad_top, pad_bot = np.floor(pad_vert).astype(int), np.ceil(pad_vert).astype(int) pad_left, pad_right = 0, 0 elif aspect < 1: # vertical image new_h = sh new_w = np.round(new_h * aspect).astype(int) pad_horz = (sw - new_w) / 2 pad_left, pad_right = np.floor(pad_horz).astype(int), np.ceil(pad_horz).astype(int) pad_top, pad_bot = 0, 0 else: # square image new_h, new_w = sh, sw pad_left, pad_right, pad_top, pad_bot = 0, 0, 0, 0 # set pad color if len(img.shape) is 3 and not isinstance(padColor, (list, tuple, np.ndarray)): # color image but only one color provided padColor = [padColor] * 3 # scale and pad scaled_img = cv2.resize(img, (new_w, new_h), interpolation=interp) scaled_img = cv2.copyMakeBorder(scaled_img, pad_top, pad_bot, pad_left, pad_right, borderType=cv2.BORDER_CONSTANT, value=padColor) return scaled_img def resize_img_keep_ratio(img_name, target_size, color=(255, 255, 255)): img = cv2.imread(img_name) old_size = img.shape[0:2] # ratio = min(float(target_size)/(old_size)) ratio = min(float(target_size[i]) / (old_size[i]) for i in range(len(old_size))) new_size = tuple([int(i * ratio) for i in old_size]) img = cv2.resize(img, (new_size[1], new_size[0])) pad_w = target_size[1] - new_size[1] pad_h = target_size[0] - new_size[0] top, bottom = pad_h // 2, pad_h - (pad_h // 2) left, right = pad_w // 2, pad_w - (pad_w // 2) img_new = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, None, color) return img_new ```
if __name__ == '__main__':
第一种方法
```handlebars v_img = cv2.imread('v.jpg') # vertical image scaled_v_img = resizeAndPad(v_img, (200, 200), 127) ```
第二种方法(推荐)
```handlebars img = 'D:/test1.jpg' target_size = [500, 100] new_image = resize_img_keep_ratio(img, target_size) cv2.imshow('result', new_image) cv2.waitKey(0) ```
以上就是 短视频软件开发,比例缩放图片不变形实现的相关代码,更多内容欢迎关注之后的文章
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现