def isImgPath(path, silent=False): """ 入力されたパスが画像か判定する [in] path: 画像か判定したいパス [in] silent: cv2.imread失敗時にエラーを表示させない場合はTrue [out] 画像ならTrue """ logger.debug('isImgPath({},{})'.format(path, silent)) if not type(path) is str: return False import imghdr if not os.path.isfile(path): if not silent: logger.error('image not found: {}'.format(path)) logger.error(fileFuncLine()) return False if imghdr.what(path) is None: if not silent: logger.error('image not found: {}'.format(path)) logger.error(fileFuncLine()) return False else: return True
def imgData(folder): """ フォルダにあるファイルから学習用データとテスト用データを取得する [in] folder: 探索するフォルダ [out] train: 取得した学習用データ [out] test: 取得したテスト用データ [out] ch: 取得したデータのチャンネル数 """ # 探索するフォルダがなければ終了 if not os.path.isdir(folder): logger.error('folder not found: {}'.format(folder)) logger.error(fileFuncLine()) exit() # 学習用データとテスト用データを発見したらTrueにする train_flg = False test_flg = False ch = 3 # フォルダ内のファイルを探索していき、 # 1. ファイル名の頭がtrain_なら学習用データとして読み込む # 2. ファイル名の頭がtest_ならテスト用データとして読み込む for l in os.listdir(folder): name, ext = os.path.splitext(os.path.basename(l)) if os.path.isdir(l): pass elif ('train_' in name) and ('.npz' in ext) and (train_flg is False): np_arr = np.load(os.path.join(folder, l)) x, y = np_arr['x'], np_arr['y'] train = tuple_dataset.TupleDataset(x, y) logger.info('{0}:\tx{1}\ty{2}'.format(l, x.shape, y.shape)) ch = x[0].shape[0] if (train._length > 0): train_flg = True elif ('test_' in name) and ('.npz' in ext) and (test_flg is False): np_arr = np.load(os.path.join(folder, l)) x, y = np_arr['x'], np_arr['y'] test = tuple_dataset.TupleDataset(x, y) logger.info('{0}:\tx{1}\ty{2}'.format(l, x.shape, y.shape)) if (test._length > 0): test_flg = True # 学習用データとテスト用データの両方が見つかった場合にのみ次のステップへ進める if (train_flg is True) and (test_flg is True): return train, test, ch else: logger.error('dataset not found in this folder: {}'.format(folder)) logger.error(fileFuncLine()) exit()
def actfun(actfun_str): """ 入力文字列から活性化関数を推定する """ if(actfun_str.lower() == 'relu'): actfun = F.relu elif(actfun_str.lower() == 'elu'): actfun = F.elu elif(actfun_str.lower() == 'c_relu'): actfun = F.clipped_relu elif(actfun_str.lower() == 'l_relu'): actfun = F.leaky_relu elif(actfun_str.lower() == 'sigmoid'): actfun = F.sigmoid elif(actfun_str.lower() == 'h_sigmoid'): actfun = F.hard_sigmoid elif(actfun_str.lower() == 'tanh'): actfun = F.tanh elif(actfun_str.lower() == 's_plus'): actfun = F.softplus elif(actfun_str.lower() == 'none'): actfun = F_None else: actfun = F.relu print('\n[Warning] {0}\n\t{1}->{2}\n'.format( fileFuncLine(), actfun_str, actfun.__name__) ) print('Activation func:', actfun.__name__) return actfun
def optimizer(opt_str): """ 入力文字列からオプティマイザを推定する """ if(opt_str.lower() == 'adam'): opt = O.Adam(amsgrad=True) elif(opt_str.lower() == 'ada_d'): opt = O.AdaDelta() elif(opt_str.lower() == 'ada_g'): opt = O.AdaGrad() elif(opt_str.lower() == 'm_sgd'): opt = O.MomentumSGD() elif(opt_str.lower() == 'n_ag'): opt = O.NesterovAG() elif(opt_str.lower() == 'rmsp'): opt = O.RMSprop() elif(opt_str.lower() == 'rmsp_g'): opt = O.RMSpropGraves() elif(opt_str.lower() == 'sgd'): opt = O.SGD() elif(opt_str.lower() == 'smorms'): opt = O.SMORMS3() else: opt = O.Adam(amsgrad=True) print('\n[Warning] {0}\n\t{1}->{2}\n'.format( fileFuncLine(), opt_str, opt.__doc__.split('.')[0]) ) print('Optimizer:', opt.__doc__.split('.')[0]) return opt
def jsonData(path, data): """ 入力されたjsonのパスからjsonを読み込み、取得したいdataの値を返す [in] path:読み込みたいjsonファイルのパス [in] data:読み込みたいデータの名称リスト [out] param: 取得した値 """ logger.debug('json read: {}'.format(path)) try: with open(path, 'r') as f: j_dict = json.load(f) except: import traceback traceback.print_exc() logger.error(fileFuncLine()) exit(1) param = [j_dict[d] for d in data if d in j_dict] logger.debug('param[{}]: {}'.format(len(data), data)) logger.debug('param[{}]: {}'.format(len(param), param)) if len(param) == 0: logger.error('json read miss: {}'.format(data)) elif len(param) == 1: return param[0] else: return param
def encodeDecode(img, ch, quality=5, ext='.jpg'): """ 入力された画像を圧縮する ※詳細はencodeDecodeNとほぼ同じなので省略 """ encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality] result, encimg = cv2.imencode(ext, img, encode_param) if False == result: print('[Error] {0}\n\timage encode failed!'.format(fileFuncLine())) exit(1) return cv2.imdecode(encimg, getCh(ch))
def blank(size, color, dtype=np.uint8, min_val=0, max_val=255): """ 単色画像を生成する [in] size: 生成する画像サイズ [h,w,ch](chがない場合は1を設定) [in] color: 色(intでグレー、tupleでカラー) [in] dtype: データ型 [in] min_val: 色の最小値 [in] max_val: 色の最大値 [out] img: 生成した単色画像 """ logger.debug('blank({},{},{},{},{})'.format(size, color, dtype.__name__, min_val, max_val)) # サイズに負数がある場合はエラー if np.min(size) < 0: logger.error('\tsize < 0: {}'.format(size)) logger.error(fileFuncLine()) exit(1) # サイズに縦横しか含まれていない場合はチャンネル追加 if len(size) == 2: logger.debug('\tsize len = 2: {}'.format(size)) size = (size[0], size[1], 1) if size[2] == 1: logger.debug('\tch = 1: {}'.format(size)) size = (size[0], size[1]) # , 1) # 色がintの場合はグレースケールとして塗りつぶす # 0 < color < 255の範囲にない場合は丸める if type(color) is int: img = np.zeros(size, dtype=dtype) if color < min_val: color = min_val elif color > max_val: color = max_val logger.debug('\t0 < color < 255: {}', color) img.fill(color) return img # チャンネルが3じゃない時は3にする if len(color) == 3 and len(size) < 3: logger.debug('\tsize len != 3: {}'.format(size)) size = (size[0], size[1], 3) img = np.zeros(size, dtype=dtype) img[:, :, :] = color return img
def encodeDecode(img, ch, quality=5, ext='.jpg'): """ 入力された画像を圧縮する ※詳細はencodeDecodeNとほぼ同じなので省略 """ logger.debug('encodeDecode({},{},{},{})'.format(img.shape, ch, quality, ext)) encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality] result, encimg = cv2.imencode(ext, img, encode_param) if False == result: logger.error('image encode failed!') logger.error(fileFuncLine()) exit(1) return cv2.imdecode(encimg, getCh(ch))
def arr2imgs(arr, norm=255, dtype=np.uint8): """ Chainerの出力をOpenCVで可視化するために変換する(画像リスト用) [in] arr: Chainerから出力された行列 [in] norm: 正規化をもとに戻す数(255であれば、0-1を0-255に変換する) [in] dtype: 変換するデータタイプ [out] OpenCV形式の画像に変換された行列 """ try: ch, size = arr.shape[1], arr.shape[2] except: print('[ERROR] input data is not img arr') print(fileFuncLine()) exit(1) y = np.array(arr).reshape((-1, size, size, ch)) * norm return np.array(y, dtype=dtype)
def modelParam(path): """ jsonで記述されたモデルパラメータ情報を読み込む [in] path: jsonファイルのパス [out] d['network']: ネットワークの種類 [out] d['unut']: 中間層のユニット数 [out] ch: 画像のチャンネル数 [out] size: 画像の分割サイズ [out] d['layer_num']: ネットワーク層の数 [out] d['shuffle_rate']: PSのshuffle rate [out] af1: 活性化関数(1) [out] af2: 活性化関数(2) """ print('model param:', path) try: with open(path, 'r') as f: d = json.load(f) except: import traceback traceback.print_exc() print(fileFuncLine()) exit() if 'network' in d: net = d['network'] else: net = 'None' if 'layer_num' in d: layer = d['layer_num'] else: layer = 0 af1 = actfun(d['actfun1']) af2 = actfun(d['actfun2']) ch = d['shape'][0] size = d['shape'][1] return \ net, d['unit'], ch, size, \ layer, d['shuffle_rate'], af1, af2
def isImgPath(name, silent=False): """ 入力されたパスが画像か判定する [in] name: 画像か判定したいパス [in] silent: cv2.imread失敗時にエラーを表示させない場合はTrue [out] 画像ならTrue """ if not type(name) is str: return False # cv2.imreadしてNoneが返ってきたら画像でないとする if cv2.imread(name) is not None: return True else: if not silent: print('[{0}] is not Image'.format(name)) print(fileFuncLine()) return False
def lossfun(lossfun_str): """ 入力文字列から損失関数を推定する """ if(lossfun_str.lower() == 'mse'): lossfun = F.mean_squared_error elif(lossfun_str.lower() == 'mae'): lossfun = F.mean_absolute_error elif(lossfun_str.lower() == 'ber'): lossfun = F.bernoulli_nll elif(lossfun_str.lower() == 'gauss_kl'): lossfun = F.gaussian_kl_divergence else: lossfun = F.mean_squared_error print('\n[Warning] {0}\n\t{1}->{2}\n'.format( fileFuncLine(), lossfun_str, lossfun.__name__) ) print('Loss func:', lossfun.__name__) return lossfun
def arr2imgs(arr, norm=255, dtype=np.uint8): """ Chainerの出力をOpenCVで可視化するために変換する(画像リスト用) [in] arr: Chainerから出力された行列 [in] norm: 正規化をもとに戻す数(255であれば、0-1を0-255に変換する) [in] dtype: 変換するデータタイプ [out] OpenCV形式の画像に変換された行列 """ try: ch, size = arr.shape[1], arr.shape[2] except: logger.error('input data is not img arr') logger.error(fileFuncLine()) exit(1) y = np.array(arr).reshape((-1, size, size, ch)) * norm # logger.debug('arr2imgs({},{},{})->{}'.format( # arr.shape, norm, dtype.__name__, y.shape # )) return np.array(y, dtype=dtype)
def jsonData(path, data): logger.debug('json read: {}'.format(path)) try: with open(path, 'r') as f: j_dict = json.load(f) except: import traceback traceback.print_exc() logger.error(fileFuncLine()) exit(1) param = [j_dict[d] for d in data if d in j_dict] logger.debug('param[{}]: {}'.format(len(data), data)) logger.debug('param[{}]: {}'.format(len(param), param)) if len(param) == 0: logger.error('json read miss: {}'.format(data)) elif len(param) == 1: return param[0] else: return param
def blank(size, color, dtype=np.uint8, min_val=0, max_val=255): """ 単色画像を生成する [in] size: 生成する画像サイズ [h,w,ch](chがない場合は1を設定) [in] color: 色(intでグレー、tupleでカラー) [in] dtype: データ型 [in] min_val: 色の最小値 [in] max_val: 色の最大値 [out] img: 生成した単色画像 """ # サイズに負数がある場合はエラー if np.min(size) < 0: print('[Error] size < 0: {0}'.format(size)) print(fileFuncLine()) exit(1) # サイズに縦横しか含まれていない場合はチャンネル追加 if len(size) == 2: size = (size[0], size[1], 1) # 色がintの場合はグレースケールとして塗りつぶす # 0 < color < 255の範囲にない場合は丸める if type(color) is int: img = np.zeros(size, dtype=dtype) if color < min_val: color = min_val elif color > max_val: color = max_val img.fill(color) return img # チャンネルが3じゃない時は3にする if size[2] != 3: size = (size[0], size[1], 3) img = np.zeros(size, dtype=dtype) img[:, :, :] = color return img
def modelParam(path): """ この関数は将来的に削除予定。 同様の機能がjsonData()にあるのでそちらを利用すること。 jsonで記述されたモデルパラメータ情報を読み込む [in] path: jsonファイルのパス [out] d['network']: ネットワークの種類 [out] d['unut']: 中間層のユニット数 [out] ch: 画像のチャンネル数 [out] size: 画像の分割サイズ [out] d['layer_num']: ネットワーク層の数 [out] d['shuffle_rate']: PSのshuffle rate [out] af1: 活性化関数(1) [out] af2: 活性化関数(2) """ logger.debug('model param: {}'.format(path)) try: with open(path, 'r') as f: d = json.load(f) except: import traceback traceback.print_exc() logger.error(fileFuncLine()) exit(1) if 'network' in d: net = d['network'] else: net = 'None' if 'layer_num' in d: layer = d['layer_num'] else: layer = 0 try: af1 = actfun(d['actfun1']) except: af1 = None try: af2 = actfun(d['actfun2']) except: af2 = None try: ch = d['shape'][0] except: ch = 0 try: size = d['shape'][1] except: size = 0 try: sr = d['shuffle_rate'] except: sr = 0 return \ net, d['unit'], ch, size, \ layer, sr, af1, af2