Python自定义修改图像的大小尺寸以及格式的缩放重构后的图像输出

输入的图片进行大小调整,由于大小被改变,因此会涉及到一些插值算法。cv2内置的有线性插值和最近邻插值等参考其他

直接上源码:

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
# Author's_name_is_NIKOLA_SS

import cv2
import numpy as np

width = 400
height = 200

img = cv2.imread(r'S:\picciicici\7126.png') # 读取图像
print ('The shape of initial graph is: {}'.format(img.shape)) # 打印原图大小
img = cv2.resize(img, (width, height), interpolation=cv2.INTER_NEAREST) # 最近邻插值缩放
print ('The changed shape of graph is: {}'.format(img.shape)) # 打印更改后图片大小

cv2.imwrite(r'S:\picciicici\new_log.jpg', img) # 保存图片格式jpg

width = 300
height = 300

img = cv2.resize(img, (width, height), interpolation=cv2.INTER_LINEAR) # 双线性插值缩放
print ('The changed shape of graph is: {}'.format(img.shape)) # 打印更改后图片大小

cv2.imwrite(r'S:\picciicici\new_log990.png', img) # 保存图片格式png

运行的结果栏输出结果如下:

The shape of initial graph is: (389, 500, 3)
The changed shape of graph is: (200, 400, 3)
The changed shape of graph is: (300, 300, 3)

Process finished with exit code 0

效果如图:
在这里插入图片描述

另外的,特别是对于需要特殊处理的图像,比如说平均池化。
平均池化。
滑窗步长都是1,但是在实际场景中,增大滑窗的步长不仅可以达到很好的效果,还可以很大程度上介绍需要处理的图像的大小。这里介绍的池化,可以认为是一种特殊的卷积运算。常用的池化方法有最大池化和平均池化,顾名思义,最大池化就是取卷积/池化区域中的最大值,而平均池化则是取平均值,主要的作用还是等效的去压缩一个图像的信息,尤其是最大池化,可以很好的保留原图像中的显著特征。

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
# Author's_name_is_NIKOLA_SS

import cv2
import numpy as np

img = cv2.imread(r'W:\\PY\newpicpic\ggffg.jpg')
print ('The shape of input img is: {}'.format(img.shape))

pooling_img = np.zeros((int(int(img.shape[0])/2),
                        int(int(img.shape[1])/2),
                        int(img.shape[2])))
for i in range(int(int(img.shape[0])/2)):
    for j in range(int(int(img.shape[1])/2)):
        pooling_img[i][j] = (img[2*i][2*j] + img[2*i][2*j+1] + img[2*i+1][2*j] + img[2*i+1][2*j+1])/4

print ('The shape of output img is: {}'.format(pooling_img.shape))
cv2.imwrite(r'W:\\PY\newpicpic\bb4d.png', pooling_img)

结果栏:

The shape of input img is: (533, 800, 3)
The shape of output img is: (266, 400, 3)

Process finished with exit code 0

图像对比显示:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海宝7号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值