一直用机器学习的算法处理自己的图片,对opencv也算是会调用,略懂点点。
有次有个朋友问我如何处理,我以前都用keras的接口自动处理来的。
后来有个实际应用中需要对发现如果需要按照指定位置进行裁剪,对,就是从中心位置裁剪128*128的大小的图像,还是需要自己写的,记录一下,同时给python和opencv的初用者一个mark:
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 11 21:26:40 2018
@author: feinix
"""
import os
import cv2
# 遍历指定目录,显示目录下的所有文件名
def CropImage4File(filepath,destpath):
pathDir = os.listdir(filepath) # list all the path or file in filepath
for allDir in pathDir:
child = os.path.join(filepath, allDir)
dest = os.path.join(destpath,allDir)
if os.path.isfile(child):
# judge whether is the dir or file
#下面写你需要进行的操作,注意缩进
image = cv2.imread(child)
sp = image.shape#obtain the image shape
sz1 = sp[0]#height(rows) of image
sz2 = sp[1]#width(colums) of image
#sz3 = sp[2]#the pixels value is made up of three primary colors, here we do not use
#你想对文件的操作
a=int(sz1/2-64) # x start
b=int(sz1/2+64) # x end
c=int(sz2/2-64) # y start
d=int(sz2/2+64) # y end
cropImg = image[a:b,c:d] #crop the image
cv2.imwrite(dest,cropImg)# write in destination path
if __name__ == '__main__':
filepath ='F:\\\maomi' # source images
destpath='F:\\maomi_resize' # resized images saved here
CropImage4File(filepath,destpath)