python高精度等比圧縮ピクチャ、圧縮ピクチャ名は元ピクチャと同じ

1843 ワード

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

path = "C:/Users/Administrator/Desktop/123/123" #          
path1 = "C:/Users/Administrator/Desktop/123" #           
filenames = os.listdir(path)

time1 = time.time()
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)
    img = Image.open(filename, "r")
    image = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
    #     
    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)

    #      ,        
    imgE = Image.fromarray(cv2.cvtColor(res, cv2.COLOR_BGR2RGB))
    gary2 = imgE.filter(ImageFilter.DETAIL)
    # #     
    gary3 = gary2.point(lambda i: i*0.9)
    img_convert_ndarray = cv2.cvtColor(np.asarray(gary3), cv2.COLOR_RGB2BGR)
    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('.png', a)[1].tofile(filename1)  #     
time2 = time.time()
print(u'    :' + str(time2 - time1) + 's')