def test_imgs2arr(self): l = cv2.imread(lenna_path) m = cv2.imread(mandrill_path) self.assertEqual(IMG.imgs2arr([l, m]).shape, (2, 3, 256, 256)) l = cv2.imread(lenna_path, IMG.getCh(1)) m = cv2.imread(mandrill_path, IMG.getCh(1)) self.assertEqual(IMG.imgs2arr([l, m]).shape, (2, 1, 256, 256))
def test_encodeDecode(self): l = cv2.imread(lenna_path) m = cv2.imread(mandrill_path) self.assertEqual(len(IMG.encodeDecodeN([l, m], 3)), 2) self.assertEqual(len(IMG.encodeDecodeN([l, m], 1)), 2) l = cv2.imread(lenna_path, IMG.getCh(1)) m = cv2.imread(mandrill_path, IMG.getCh(1)) self.assertEqual(len(IMG.encodeDecodeN([l, m], 3)), 2) self.assertEqual(len(IMG.encodeDecodeN([l, m], 1)), 2)
def main(args): # 入力のカラー画像を読み込む if IMG.isImgPath(args.color): print('color image read:\t', args.color) x = cv2.imread(args.color, IMG.getCh(3)) else: print('[ERROR] color image not found:', args.color) exit() # 正解のモノクロ画像を読み込む if IMG.isImgPath(args.duotone): print('duotone image read:\t', args.duotone) y = edgeDetect(cv2.imread(args.duotone, IMG.getCh(1)), x) else: print('[ERROR] duotone image not found:', args.duotone) exit() # 入力画像と正解画像を # [1] 反転して増やす [flip()] # [2] 正方形に分割する [splitSQN()] print('split and rotate images...') x, _ = IMG.splitSQN(IMG.flip(x, args.augmentation), args.img_size, args.round) y, _ = IMG.splitSQN(IMG.flip(y, args.augmentation), args.img_size, args.round) # 画像の並び順をシャッフルするための配列を作成する # colorとmonoの対応を崩さないようにシャッフルしなければならない # また、train_sizeで端数を切り捨てる print('shuffle images...') shuffle = np.random.permutation(range(len(x))) train_size = int(len(x) * args.train_per_all) print('train/all : {0}/{1}'.format(train_size, len(x))) # float16で保存することでファイルサイズを軽減できる # 情報量は落ちるが問題ないレベル dtype = np.float16 train_x = IMG.imgs2arr(x[shuffle[:train_size]], dtype=dtype) train_y = IMG.imgs2arr(y[shuffle[:train_size]], dtype=dtype) test_x = IMG.imgs2arr(x[shuffle[train_size:]], dtype=dtype) test_y = IMG.imgs2arr(y[shuffle[train_size:]], dtype=dtype) print('train x/y:{0}/{1}'.format(train_x.shape, train_y.shape)) print('test x/y:{0}/{1}'.format(test_x.shape, test_y.shape)) # 生成したデータをnpz形式でデータセットとして保存する # ここで作成したデータの中身を確認する場合はnpz2jpg.pyを使用するとよい print('save npz...') saveNPZ(train_x, train_y, 'train', args.out_path, args.img_size) saveNPZ(test_x, test_y, 'test', args.out_path, args.img_size)
def getImage(jpg_path, ch, img_size, img_num, seed): """ 画像を読み込んでランダムに取得して連結する [in] jpg_path: 入力画像のパス [in] ch: 画像を読み込むチャンネル数 [in] img_size: 画像を分割するサイズ [in] img_num: 使用する画像の数 [in] seed: 乱数シード [out] 連結された画像(縦長) """ ch_flg = IMG.getCh(ch) # 画像を読み込み imgs = [cv2.imread(jpg, ch_flg) for jpg in jpg_path if IMG.isImgPath(jpg)] # 画像を分割し imgs, size = IMG.splitSQN(imgs, img_size) # ほとんど白い画像を除去し imgs = np.array(IMG.whiteCheckN(imgs)) if (seed >= 0): np.random.seed(seed) # ランダムに取得する shuffle = np.random.permutation(range(len(imgs))) return np.vstack(imgs[shuffle[:img_num]])
def main(args): # jsonファイルから学習モデルのパラメータを取得する n_out, n_unit, actfun = GET.jsonData(args.param, ['n_out', 'n_unit', 'actfun']) # 学習モデルを生成する model = L.Classifier( CNT(n_out, n_unit, GET.actfun(actfun), base=L.ResNet50Layers(None))) # load_npzのpath情報を取得し、学習済みモデルを読み込む load_path = F.checkModelType(args.model) try: chainer.serializers.load_npz(args.model, model, path=load_path) except: import traceback traceback.print_exc() print(F.fileFuncLine()) exit() # GPUの設定 if args.gpu >= 0: chainer.cuda.get_device_from_id(args.gpu).use() model.to_gpu() # else: # model.to_intel64() # 画像の生成 if (args.human_num < 0): h_num = np.random.randint(0, 4) else: h_num = args.human_num if args.image == '': x = create(args.other_path, args.human_path, args.background_path, args.obj_size, args.img_size, args.obj_num, h_num, 1)[0] print(x.shape) elif IMG.isImgPath(args.image): x = cv2.cvtColor(cv2.imread(args.image, IMG.getCh(0)), cv2.COLOR_RGB2BGR) else: print('input image path is not found:', args.image) exit() t = img2resnet(np.array(x)) # 学習モデルを実行する with chainer.using_config('train', False): st = time.time() y = model.predictor(t) num = y[0].data.argmax() print('exec time: {0:.2f}[s]'.format(time.time() - st)) print('result:', num) # 生成結果を保存する name = F.getFilePath(args.out_path, 'predict-' + str(num).zfill(2), '.jpg') print('save:', name) cv2.imwrite(name, x) cv2.imshow(name, x) cv2.waitKey()
def test_getCh(self): self.assertEqual(IMG.getCh(-1), cv2.IMREAD_UNCHANGED) self.assertEqual(IMG.getCh(0), cv2.IMREAD_UNCHANGED) self.assertEqual(IMG.getCh(1), cv2.IMREAD_GRAYSCALE) self.assertEqual(IMG.getCh(2), cv2.IMREAD_UNCHANGED) self.assertEqual(IMG.getCh(3), cv2.IMREAD_COLOR) self.assertEqual(IMG.getCh(4), cv2.IMREAD_UNCHANGED) self.assertEqual(IMG.getCh(2.5), cv2.IMREAD_UNCHANGED)
def on_modified(self, event): path, name, ext = super().on_modified(event) if ('jpg' in ext.lower()): print('duotone:{0}'.format(os.path.join(self.copy, path))) time.sleep(1) # 学習モデルを入力画像ごとに実行する with chainer.using_config('train', False): img = IMG.resize(cv2.imread(path, IMG.getCh(3)), self.rate) img = predict(self.model, IMG.splitSQ(img, self.size), self.batch, img.shape, self.gpu) cv2.imwrite(os.path.join(self.copy, name), img)
def main(args): # jsonファイルから学習モデルのパラメータを取得する net, unit, ch, size, layer, sr, af1, af2 = GET.modelParam(args.param) # 学習モデルを生成する if net == 0: from Lib.network import JC_DDUU as JC else: from Lib.network2 import JC_UDUD as JC model = L.Classifier( JC(n_unit=unit, n_out=1, rate=sr, actfun1=af1, actfun2=af2)) # load_npzのpath情報を取得し、学習済みモデルを読み込む load_path = F.checkModelType(args.model) try: chainer.serializers.load_npz(args.model, model, path=load_path) except: import traceback traceback.print_exc() print(F.fileFuncLine()) exit() # GPUの設定 if args.gpu >= 0: chainer.cuda.get_device_from_id(args.gpu).use() model.to_gpu() else: model.to_intel64() # 高圧縮画像の生成 org_imgs = [ cv2.imread(name, IMG.getCh(ch)) for name in args.jpeg if IMG.isImgPath(name) ] imgs = [] # 学習モデルを入力画像ごとに実行する for i, ei in enumerate(org_imgs): with chainer.using_config('train', False): img = predict(model, IMG.splitSQ(ei, size), args.batch, ei.shape, sr, args.gpu) imgs.append(IMG.resize(img, args.out_rate)) for img in imgs: cv2.imshow('view', img) cv2.waitKey() # 生成結果を保存する name = F.getFilePath(args.out_path, 'comp-' + str(i * 10 + 1).zfill(3), '.jpg') print('save:', name) cv2.imwrite(name, img)
def test_split(self): l = cv2.imread(lenna_path) m = cv2.imread(mandrill_path) imgs, split = IMG.splitSQN([l, m], 32) self.assertEqual(imgs.shape, (128, 32, 32, 3)) self.assertEqual(split, (8, 8)) imgs, split = IMG.splitSQN([l, m], 0) self.assertEqual(imgs.shape, (512, 2, 2)) self.assertEqual(split, (1, 1)) imgs, split = IMG.splitSQN([l, m], 32, 10) self.assertEqual(imgs.shape, (120, 32, 32, 3)) self.assertEqual(split, (8, 8)) imgs, split = IMG.splitSQN([l, m], 32, 100) self.assertEqual(imgs.shape, (100, 32, 32, 3)) self.assertEqual(split, (8, 8)) imgs, split = IMG.splitSQN([l, m], 32, 1000) self.assertEqual(imgs.shape, (128, 32, 32, 3)) self.assertEqual(split, (8, 8)) print(l.shape, m.shape) imgs, split = IMG.splitSQN([l, m], 1024) self.assertEqual(imgs.shape, (2, 256, 256, 3)) self.assertEqual(split, (1, 1)) bk = IMG.blank((100, 120, 3), 255) imgs, split = IMG.splitSQN([bk], 1024) self.assertEqual(imgs.shape, (1, 100, 100, 3)) self.assertEqual(split, (1, 1)) l = cv2.imread(lenna_path, IMG.getCh(1)) m = cv2.imread(mandrill_path, IMG.getCh(1)) imgs, split = IMG.splitSQN([l, m], 32) self.assertEqual(imgs.shape, (128, 32, 32)) self.assertEqual(split, (8, 8))
def getImgN(path): """ 入力されたフォルダにある画像を全て読み込む [in] path: [out] 読みこんだ画像リスト """ if not os.path.isdir(path): print('path not found:', path) exit(1) from os.path import join as opj return np.array([ cv2.imread(opj(path, f), IMG.getCh(0)) for f in os.listdir(path) if IMG.isImgPath(opj(path, f)) ])
def main(args): # jsonファイルから学習モデルのパラメータを取得する net, unit, ch, size, layer, sr, af1, af2 = GET.modelParam(args.param) # 学習モデルを生成する model = L.Classifier( JC(n_unit=unit, n_out=ch, rate=sr, actfun1=af1, actfun2=af2)) # load_npzのpath情報を取得し、学習済みモデルを読み込む load_path = F.checkModelType(args.model) try: chainer.serializers.load_npz(args.model, model, path=load_path) except: import traceback traceback.print_exc() print(F.fileFuncLine()) exit() # GPUの設定 if args.gpu >= 0: chainer.cuda.get_device_from_id(args.gpu).use() model.to_gpu() else: model.to_intel64() # 画像の生成 if args.image == '': x, _ = create(args.other_path, args.human_path, args.background_path, args.obj_size, args.img_size, args.obj_num, 1, 1) elif IMG.isImgPath(args.image): x = cv2.imread(args.image, IMG.getCh(0)) w, h = x.shape[:2] x = np.array(x).reshape(1, w, h, -1) else: print('input image path is not found:', args.image) exit() # 学習モデルを実行する with chainer.using_config('train', False): img = IMG.resize(predict(model, x, args.batch, args.gpu), 1 / sr) # 生成結果を保存する name = F.getFilePath(args.out_path, 'predict', '.jpg') print('save:', name) img = np.hstack([x[0], img]) cv2.imwrite(name, img) cv2.imshow(name, img) cv2.waitKey()
def main(args): # OpenCV形式で画像を読み込むために # チャンネル数をOpenCVのフラグ形式に変換する ch = IMG.getCh(args.channel) # OpenCV形式で画像をリストで読み込む print('read images...') imgs = [cv2.imread(name, ch) for name in args.jpeg if IMG.isImgPath(name)] if len(imgs) == 0: print('image get error') exit(1) # 画像を圧縮して分割する(学習の入力データに相当) print('split images...') x, _ = IMG.splitSQN( IMG.flipN(IMG.encodeDecodeN(imgs, ch, args.quality), args.flip_num), args.img_size, args.round) # 画像を分割する(正解データに相当) y, _ = IMG.splitSQN(IMG.flipN(imgs, args.flip_num), args.img_size, args.round) # 画像の並び順をシャッフルするための配列を作成する # compとrawの対応を崩さないようにシャッフルしなければならない # また、train_sizeで端数を切り捨てる # データをint8からfloat16に変えるとデータ数が大きくなるので注意 print('shuffle images...') dtype = np.float16 shuffle = np.random.permutation(range(len(x))) train_size = int(len(x) * args.train_per_all) train_x = IMG.imgs2arr(x[shuffle[:train_size]], dtype=dtype) train_y = IMG.imgs2arr(y[shuffle[:train_size]], dtype=dtype) test_x = IMG.imgs2arr(x[shuffle[train_size:]], dtype=dtype) test_y = IMG.imgs2arr(y[shuffle[train_size:]], dtype=dtype) print('train x/y:{0}/{1}'.format(train_x.shape, train_y.shape)) print('test x/y:{0}/{1}'.format(test_x.shape, test_y.shape)) # 生成したデータをnpz形式でデータセットとして保存する # ここで作成したデータの中身を確認する場合はnpz2jpg.pyを使用するとよい print('save npz...') saveNPZ(train_x, train_y, 'train', args.out_path, args.img_size) saveNPZ(test_x, test_y, 'test', args.out_path, args.img_size)