python等比压缩图片到固定大小,不足的留白

代码中为了切换图片的读取格式将图片保存后又读取了一遍,太过繁琐,需要改进的代码请前往
https://blog.csdn.net/lidongxx/article/details/92769009

from PIL import Image
from PIL import ImageFilter
import cv2
import time
import os
import numpy as np
im = Image.new("RGB", (400, 400), "white")
imndarray = np.array(im)


path = "C:/Users/Administrator/Desktop/E9-211-JPG/E9-JPG"
path1 = "C:/Users/Administrator/Desktop/newE9-JPG"
filenames = os.listdir(path)

time1 = time.time()
#读入图像
#resp = urllib.request.urlopen(url)
#image = np.asarray(bytearray(resp.read()), dtype="uint8")
#image = cv2.imdecode(image, cv2.IMREAD_COLOR)
for i in filenames:
    filename = os.path.join(path, i)
    filename1 = os.path.join(path1, i)
    image = cv2.imdecode(np.fromfile(filename, dtype=np.uint8), -1)
    #双三次插值
    height, width = image.shape[:2]  #获取原图像的水平方向尺寸和垂直方向尺寸。
    temp = max(height, width)
    multemp = temp/400
    if height > width:
        res = cv2.resize(image, (int(width / multemp), 400), interpolation=cv2.INTER_AREA)
    elif height < width:
        res = cv2.resize(image, (400, int(height / multemp)), interpolation=cv2.INTER_AREA)
    else:
        res = cv2.resize(image, (400, 400), interpolation=cv2.INTER_AREA)
    cv2.imwrite("C:/Users/Administrator/Desktop/temp/101.jpg", res)
    imgE = Image.open("C:/Users/Administrator/Desktop/temp/101.jpg")
    gary2 = imgE.filter(ImageFilter.DETAIL)
    #图像点运算
    gary3 = gary2.point(lambda i: i*0.9)
    #savePath = (filename1)
    img_convert_ndarray = np.array(gary3)
    height1, width1 = img_convert_ndarray.shape[:2]
    temph = int((400 - height1)/2)
    tempw = int((400 - width1)/2)
    a = cv2.copyMakeBorder(img_convert_ndarray, temph, 400-temph-height1,tempw, 400-tempw-width1, cv2.BORDER_CONSTANT, value=[255, 255, 255])
    cv2.imencode('.jpg', a)[1].tofile(filename1)  # 保存图片
time2 = time.time()
print (u'总共耗时:' + str(time2 - time1) + 's')
发布了19 篇原创文章 · 获赞 9 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览