我目標文件夾下有一大批圖片,我要把它轉變為指定尺寸大小的圖片,用pthon和opencv實現的。
以上為原圖片。
import cv2 import os # 按指定圖像大小調整尺寸 def resize_image(image, height = 640, width = 480): top, bottom, left, right = (0,0,0,0) # 獲取圖片尺寸 h, w, _ = image.shape # 對於長寬不等的圖片,找到最長的一邊 longest_edge = max(h,w) # 計算短邊需要增加多少像素寬度才能與長邊等長(相當於padding,長邊的padding為0,短邊才會有padding) if h < longest_edge: dh = longest_edge - h top = dh // 2 bottom = dh - top elif w < longest_edge: dw = longest_edge - w left = dw // 2 right = dw - left else: pass # pass是空語句,是為了保持程序結構的完整性。pass不做任何事情,一般用做占位語句。 # RGB顏色 BLACK = [0,0,0] # 給圖片增加padding,使圖片長、寬相等 # top, bottom, left, right分別是各個邊界的寬度,cv2.BORDER_CONSTANT是一種border type,表示用相同的顏色填充 constant = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value = BLACK) # 調整圖像大小並返回圖像,目的是減少計算量和內存占用,提升訓練速度 return cv2.resize(constant, (height, width)) def read__image(path_name): num = 0 for dir_image in os.listdir(path_name): # os.listdir() 方法用於返回指定的文件夾包含的文件或文件夾的名字的列表 full_path = os.path.abspath(os.path.join(path_name,dir_image)) if os.path.isdir(full_path): #如果是文件夾,繼續遞歸調用 read_training_data(full_path) else: #如果是文件了 if dir_image.endswith('.JPG'): image = cv2.imread(full_path) image = resize_image(image) #將尺寸調整好的圖片保存起來 image_name = '%s%d.jpg' % ('resize_image',num) # 注意這里圖片名一定要加上擴展名,否則后面imwrite的時候會報錯 cv2.imwrite(image_name, image) num = num + 1 if __name__=='__main__': read__image('C:/Users/baideguo/dataset/JPEGImages/')
我把原圖片大小為3024 x 4032轉變為了640*480大小的圖片