python 裁剪圖片;位深度不變

weixin_44939146發表於2020-11-03

裁剪圖片,20562124->512512
先將圖片縮小4倍,變為531514;然後提取前512個畫素,變為512512

#裁剪圖片,使圖片變為512*512
import os
import cv2
import imutils
from PIL import Image

def resize_crop_image(image):
    (h, w) = image.shape[:2]
    image = imutils.resize(image, width=531,inter=cv2.INTER_AREA)
    (h, w) = image.shape[:2]
    image = image[0:512, 0:512]
    return cv2.resize(image, (512, 512),interpolation=cv2.INTER_AREA)

if __name__ =="__main__":
#讀取固定資料夾下的所有圖片
    filePath = 'F:/AI/glaucoma_set/gla_img_120_Chall/Annotation-Training400/Disc_Cup_Masks/Non-Glaucoma/'
    savePath = 'F:/AI/glaucoma_set/gla_img_120_Chall/Annotation-Training400/Disc_Cup_Masks/Non-Glaucoma_512/'
    name = os.listdir(filePath)
    for i in name:
        image_path = os.path.join(filePath,i)
        image_save_Path = os.path.join(savePath,i)
        #cv2.IMREAD_ANYCOLOR很重要,不會改變圖片的位深度
        image = cv2.imread(image_path, cv2.IMREAD_ANYCOLOR)
        img = resize_crop_image(image)
        cv2.imwrite(image_save_Path, img)

相關文章