用opencv生成图片缩略图

由于服务器带宽太小,网站图片加载的太慢了,所以不得不给图片添加缩略图来做显示,点击查看以后再显示大图。图片比较多,就用opencv来个批量的转换了:

import cv2
import os

def generateThumbnails(path):   
# 整个文件夹路径下的图片生成方形缩略图
    dirs = os.listdir(path)
    thumbnailsPath = path + "/Thumbnails"

    for dir in dirs:
        if os.path.splitext(dir)[1]== ".jpg":
            img = cv2.imread(path+"/"+dir)

            height = img.shape[0]  # 图片高度
            width = img.shape[1]   # 图片宽度

            # 裁剪图片为正方形 (按照短边裁剪,因为有的图片竖着,有的横着)
            rct = height if height<=width else width  # 选取短边
            marginLeft = int((width - rct)/2)  # 截取的横边距
            marginTop = int((height - rct)/2)  # 截取的纵边距

            img1 = img[marginTop:marginTop + rct,marginLeft:marginLeft + rct]  
            # 截取图片的正中间部分(数组前一组为数直方向取像素,后一组为横轴方向取像素)
            img2 = cv2.resize(img1,(100,100))      # 生成图片的大小修改为 100*100

            if(not os.path.exists(thumbnailsPath)):
                os.makedirs(thumbnailsPath)
            cv2.imwrite(thumbnailsPath+"/"+dir,img2)

if __name__ == '__main__':
    path = "E:/myblogweb/src/main/resources/static/source/photosIcon"   # 文件夹名
    generateThumbnails(path)

功能为将jpg图片处理成100*100的缩略图存储在Thumbnails文件夹下。

如果不需要方形,直接等比缩小,就直接resize就行了:

import cv2
import os

def generateThumbnails(path):   
    dirs = os.listdir(path)
    thumbnailsPath = path + "/Thumbnails"

    for dir in dirs:
        if os.path.splitext(dir)[1]== ".jpg":
            img = cv2.imread(path+"/"+dir)

            height = img.shape[0]  # 图片高度
            width = img.shape[1]   # 图片宽度
            img1 = cv2.resize(img,(100,int(100/width*height)))    
            if(not os.path.exists(thumbnailsPath)):
                os.makedirs(thumbnailsPath)
            cv2.imwrite(thumbnailsPath+"/"+dir,img1)

if __name__ == '__main__':
    path = "E:/myblogweb/src/main/resources/static/source/photosIcon"   
    generateThumbnails(path)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值