轉自
http://www.cnblogs.com/neo-T/p/6477378.html
import os, sys
import cv2
#按照指定圖像大小調整尺寸
def resize_image(image, height, width):
top, bottom, left, right = (0, 0, 0, 0)
#擷取圖像尺寸
h, w, _ = image.shape
#對于長寬不相等的圖檔,找到最長的一邊
longest_edge = max(h, w)
#計算短邊需要增加多上像素寬度使其與長邊等長
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
#RGB顔色
BLACK = [0, 0, 0]
#給圖像增加邊界,是圖檔長、寬等長,cv2.BORDER_CONSTANT指定邊界顔色由value指定
constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value = BLACK)
#調整圖像大小并傳回
return cv2.resize(constant, (height, width))
def resizeImg(path_name, newpath):
for dir_item in os.listdir(path_name):
#從初始路徑開始疊加,合并成可識别的操作路徑
full_path = os.path.abspath(os.path.join(path_name, dir_item))
if os.path.isdir(full_path): #如果是檔案夾,繼續遞歸調用
read_path(full_path)
else: #檔案
if dir_item.endswith('.jpg'):
image = cv2.imread(full_path)
image = resize_image(image, 640, 640)
cv2.imwrite(newpath + '/' + dir_item, image)
def main():
# 調整圖檔大小
f = 'J:/images/old'
fnew = 'J:/images/new' # resize後的圖檔存儲路徑
resizeImg(f, fnew)
if __name__ == "__main__":
main()