#はじめに
この記事はNoteで連載している記事で扱っているCode部分のみを切り出しています。技術背景等にご興味がある方はNoteの記事の方をご参照ください。
#helperの実装
画像の入出力を多用するのでそれらをhelperとしてまとめて実装しておきます。そうすることでCodeが見やすくなりますし、メンテナンスが楽になります。使用するライブラリーは以下となります。事前にpip等でインストールしておいてください。
- glob
- OpenCV
- numpy
それでは実際の実装を記載します。
###指定したFolder内のファイル一覧作成
globを使用し、指定したFolder内で指定した拡張子を持つファイルの絶対パスリストを作成します。相対バスでも良いですが、後々絶対パスの方が扱いやすいので絶対パスで取得します。
def make_file_path_list(path: str, ext: str) -> [str]:
""" Make file path list from path and ext information
Parameters
-----------
path :str
project path
ext :str
specific the file extention in order to make path list
Returns
-----------
file path list :[str]
list of file path under the path with the specialied extention
"""
path_str = path + '*.' + ext
return glob.glob(path_str)
次に、得られた絶対パスのリストを元に画像データを読み込みます。PGMファイルであればあまり意味はないですが、一応慣例としてRGBの並びに変更しておきます。OpenCVはDefalt設定でBGRで読み込むので他の処理との整合性を保つためにRGBとしています。
def read_img_from_path(filepath: [str], width: int, height: int):
""" Read image file from path list
Parameters
----------
filepath :[str]
File list for image reading
width :int
Output image width
height: int
Output iamge height
Returns
----------
Return the read image data as RGB format
"""
stocker = []
for path in filepath:
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, dsize=(width, height), interpolation = cv2.INTER_CUBIC)
stocker.append(img)
return stocker
書き出す方もここで実装しておきましょう。引数として書き出す先のパスリストとイメージデーター及び出力Formatを指定しています。特に何も指定しなければJPEGフォーマットで出力されます。
def write_img_to_path(outpath: str, filepaths: [str], imgs: [np.ndarray], ext: str='jpg'):
""" write images to path list
Parameters
-----------
outpath: str
ouput path
filepath: [str]
file path list for file saving
imgs: [np.ndarray]
image data
ext: str
file format and define extention
"""
for idx, filepath in enumerate(filepaths):
# extract file name
filename = filepath.split('/')[-1]; filename = filename.split('.')[0]
# make output file path from filename and extention
output_file_path = outpath + filename + '.' + ext
# output images
cv2.imwrite(output_file_path, imgs[idx])
後々、Left画像か、Right画像かを判断する必要があるため画像ファイル名からLeftまたはRightを切り出して判断する関数を実装しておきます。Leftの画像であればTrueを返し、RightであればFalseを返します。
def loc_detector_from_name(file_name: str) -> bool:
""" Split location information from file name and return location info
Parameters
-----------
file_name: str
file name which includes location info such as 'left' or 'right'
Returns
-----------
loc: bool
return location info as boolian, True: 'left', False: 'right'
"""
loc = file_name.split('_')[-1]; loc = loc.split('.')[0]
if loc == 'left':
return True
return False
後ほど、画像処理で0.0~1.0の範囲に画素値を規格化するので、それ用の関数も定義しておきます。
def normarize_img_data(img: np.ndarray, max_value: int = 255):
""" Normarize image data, find min_value and max_value, and normarize
img: np.ndarray
original image data
max_value: int
define maximum value after normarization
"""
# get min, max and range for normarization
min_value = img.min()
max_value = img.max()
value_range = max_value - min_value
# normalized image
norm_img = (img - min_value) / value_range * max_value
# return
return norm_img.astype(np.uint8)
以上でhalperの準備は終わりとなります。