input
stringlengths
0
929
output
stringlengths
0
10.3k
task
stringclasses
3 values
index
int64
0
5.38k
liscence
stringclasses
4 values
source
stringclasses
15 values
instruction
stringlengths
13
3.45k
import cv2 # function: BGR -> RGB def BGR2RGB(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # RGB > BGR img[:, :, 0] = r img[:, :, 1] = g img[:, :, 2] = b return img # Read image img = cv2.imread("sample.jpg") # BGR -> RGB img = BGR2RGB(img) # Save result cv2.imwrite("out.jpg", img) cv2.imshow("result", img) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
200
MIT
gasyori_100_knocks
pythonを用いて、画像を読み込み、RGBをBGRの順に入れ替えよ。
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Read image img = cv2.imread("sample.jpg").astype(np.float) # Grayscale out = BGR2GRAY(img) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
201
MIT
gasyori_100_knocks
pythonを用いて、画像をグレースケールにせよ。 グレースケールとは、画像の輝度表現方法の一種であり下式で計算される。 Y = 0.2126 R + 0.7152 G + 0.0722 B
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # binalization def binarization(img, th=128): img[img < th] = 0 img[img >= th] = 255 return img # Read image img = cv2.imread("sample.jpg").astype(np.float32) # Grayscale out = BGR2GRAY(img) # Binarization out = binarization(out) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
202
MIT
gasyori_100_knocks
pythonを用いて、画像を二値化せよ。 二値化とは、画像を黒と白の二値で表現する方法である。 ここでは、グレースケールにおいて閾値を128に設定し、下式で二値化する。 y = { 0 (if y < 128) 255 (else)
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Otsu Binalization def otsu_binarization(img, th=128): imax_sigma = 0 max_t = 0 # determine threshold for _t in range(1, 255): v0 = out[np.where(out < _t)] m0 = np.mean(v0) if len(v0) > 0 else 0. w0 = len(v0) / (H * W) v1 = out[np.where(out >= _t)] m1 = np.mean(v1) if len(v1) > 0 else 0. w1 = len(v1) / (H * W) sigma = w0 * w1 * ((m0 - m1) ** 2) if sigma > max_sigma: max_sigma = sigma max_t = _t # Binarization print("threshold >>", max_t) th = max_t out[out < th] = 0 out[out >= th] = 255 return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Grayscale out = BGR2GRAY(img) # Otsu's binarization out = otsu_binalization(out) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
203
MIT
gasyori_100_knocks
pythonを用いて、大津の二値化を実装せよ。 大津の二値化とは判別分析法と呼ばれ、二値化における分離の閾値を自動決定する手法である。 これは**クラス内分散**と**クラス間分散**の比から計算される。 - 閾値t未満をクラス0, t以上をクラス1とする。 - w0, w1 ... 閾値tにより分離された各クラスの画素数の割合 (w0 + w1 = 1を満たす) - S0^2, S1^2 ... 各クラスの画素値の分散 - M0, M1 ... 各クラスの画素値の平均値 とすると、 クラス内分散 Sw^2 = w0 * S0^2 + w1 * S1^2 クラス間分散 Sb^2 = w0 * (M0 - Mt)^2 + w1 * (M1 - Mt)^2 = w0 * w1 * (M0 - M1) ^2 画像全体の画素の分散 St^2 = Sw^2 + Sb^2 = (const) 以上より、分離度は次式で定義される。 分離度 X = Sb^2 / Sw^2 = Sb^2 / (St^2 - Sb^2) となり、 argmax_{t} X = argmax_{t} Sb^2 となる。すなわち、Sb^2 = w0 * w1 * (M0 - M1) ^2 が最大となる、閾値tを二値化の閾値とすれば良い。
import cv2 import numpy as np # BGR -> HSV def BGR2HSV(_img): img = _img.copy() / 255. hsv = np.zeros_like(img, dtype=np.float32) # get max and min max_v = np.max(img, axis=2).copy() min_v = np.min(img, axis=2).copy() min_arg = np.argmin(img, axis=2) # H hsv[..., 0][np.where(max_v == min_v)]= 0 ## if min == B ind = np.where(min_arg == 0) hsv[..., 0][ind] = 60 * (img[..., 1][ind] - img[..., 2][ind]) / (max_v[ind] - min_v[ind]) + 60 ## if min == R ind = np.where(min_arg == 2) hsv[..., 0][ind] = 60 * (img[..., 0][ind] - img[..., 1][ind]) / (max_v[ind] - min_v[ind]) + 180 ## if min == G ind = np.where(min_arg == 1) hsv[..., 0][ind] = 60 * (img[..., 2][ind] - img[..., 0][ind]) / (max_v[ind] - min_v[ind]) + 300 # S hsv[..., 1] = max_v.copy() - min_v.copy() # V hsv[..., 2] = max_v.copy() return hsv def HSV2BGR(_img, hsv): img = _img.copy() / 255. # get max and min max_v = np.max(img, axis=2).copy() min_v = np.min(img, axis=2).copy() out = np.zeros_like(img) H = hsv[..., 0] S = hsv[..., 1] V = hsv[..., 2] C = S H_ = H / 60. X = C * (1 - np.abs( H_ % 2 - 1)) Z = np.zeros_like(H) vals = [[Z,X,C], [Z,C,X], [X,C,Z], [C,X,Z], [C,Z,X], [X,Z,C]] for i in range(6): ind = np.where((i <= H_) & (H_ < (i+1))) out[..., 0][ind] = (V - C)[ind] + vals[i][0][ind] out[..., 1][ind] = (V - C)[ind] + vals[i][1][ind] out[..., 2][ind] = (V - C)[ind] + vals[i][2][ind] out[np.where(max_v == min_v)] = 0 out = np.clip(out, 0, 1) out = (out * 255).astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # RGB > HSV hsv = BGR2HSV(img) # Transpose Hue hsv[..., 0] = (hsv[..., 0] + 180) % 360 # HSV > RGB out = HSV2BGR(img, hsv) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows() out = np.clip(out, 0, 1) out = (out * 255).astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # RGB > HSV hsv = BGR2HSV(img) # Transpose Hue hsv[..., 0] = (hsv[..., 0] + 180) % 360 # HSV > RGB out = HSV2BGR(img, hsv) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
204
MIT
gasyori_100_knocks
pythonを用いて、HSV変換を実装して、色相Hを反転せよ。 HSV変換とは、Hue(色相)、Saturation(彩度)、Value(明度) で色を表現する手法である。
import cv2 import numpy as np # Dicrease color def dicrease_color(img): out = img.copy() out = out // 64 * 64 + 32 return out # Read image img = cv2.imread("imori.jpg") # Dicrease color out = dicrease_color(img) cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
205
MIT
gasyori_100_knocks
pythonを用いて、画像の値を256^3から4^3、すなわちR,G,B in {32, 96, 160, 224}の各4値に減色せよ。これは量子化操作である。各値に関して、以下の様に定義する。 val = { 32 ( 0 <= val < 64) 96 ( 64 <= val < 128) 160 (128 <= val < 192) 224 (192 <= val < 256)
import cv2 import numpy as np # average pooling def average_pooling(img, G=8): out = img.copy() H, W, C = img.shape Nh = int(H / G) Nw = int(W / G) for y in range(Nh): for x in range(Nw): for c in range(C): out[G*y:G*(y+1), G*x:G*(x+1), c] = np.mean(out[G*y:G*(y+1), G*x:G*(x+1), c]).astype(np.int) return out # Read image img = cv2.imread("imori.jpg") # Average Pooling out = average_pooling(img) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
206
MIT
gasyori_100_knocks
ここでは画像をグリッド分割(ある固定長の領域に分ける)し、かく領域内(セル)の平均値でその領域内の値を埋める。このようにグリッド分割し、その領域内の代表値を求める操作はPooling(プーリング)と呼ばれる。これらプーリング操作はCNN(Convolutional Neural Network) において重要な役割を持つ。 これは次式で定義される。 v = 1/|R| * Sum_{i in R} v_i ここではpythonを用いて、128x128のimori.jpgを8x8にグリッド分割し、平均プーリングせよ。
import cv2 import numpy as np # max pooling def max_pooling(img, G=8): # Max Pooling out = img.copy() H, W, C = img.shape Nh = int(H / G) Nw = int(W / G) for y in range(Nh): for x in range(Nw): for c in range(C): out[G*y:G*(y+1), G*x:G*(x+1), c] = np.max(out[G*y:G*(y+1), G*x:G*(x+1), c]) return out # Read image img = cv2.imread("imori.jpg") # Max pooling out = max_pooling(img) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
207
MIT
gasyori_100_knocks
pythonを用いて、128x128のimori.jpgを8x8にグリッド分割し、最大値でプーリングせよ。
import cv2 import numpy as np # Gaussian filter def gaussian_filter(img, K_size=3, sigma=1.3): if len(img.shape) == 3: H, W, C = img.shape else: img = np.expand_dims(img, axis=-1) H, W, C = img.shape ## Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=np.float) out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float) ## prepare Kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(-pad, -pad + K_size): for y in range(-pad, -pad + K_size): K[y + pad, x + pad] = np.exp( -(x ** 2 + y ** 2) / (2 * (sigma ** 2))) K /= (2 * np.pi * sigma * sigma) K /= K.sum() tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.sum(K * tmp[y: y + K_size, x: x + K_size, c]) out = np.clip(out, 0, 255) out = out[pad: pad + H, pad: pad + W].astype(np.uint8) return out # Read image img = cv2.imread("imori_noise.jpg") # Gaussian Filter out = gaussian_filter(img, K_size=3, sigma=1.3) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
208
MIT
gasyori_100_knocks
pythonを用いて、ガウシアンフィルタ(3x3、標準偏差1.3)を実装し、imori_noise.jpgのノイズを除去せよ。 ガウシアンフィルタとは画像の平滑化(滑らかにする)を行うフィルタの一種であり、ノイズ除去にも使われる。 ノイズ除去には他にも、メディアンフィルタ、平滑化フィルタ、LoGフィルタなどがある。 ガウシアンフィルタは注目画素の周辺画素を、ガウス分布による重み付けで平滑化し、次式で定義される。このような重みはカーネルやフィルタと呼ばれる。 ただし、画像の端はこのままではフィルタリングできないため、画素が足りない部分は0で埋める。これを0パディングと呼ぶ。かつ、重みは正規化する。(sum g = 1) 重みはガウス分布から次式になる。
import cv2 import numpy as np # Median filter def median_filter(img, K_size=3): H, W, C = img.shape ## Zero padding pad = K_size // 2 out = np.zeros((H + pad*2, W + pad*2, C), dtype=np.float) out[pad:pad+H, pad:pad+W] = img.copy().astype(np.float) tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad+y, pad+x, c] = np.median(tmp[y:y+K_size, x:x+K_size, c]) out = out[pad:pad+H, pad:pad+W].astype(np.uint8) return out # Read image img = cv2.imread("imori_noise.jpg") # Median Filter out = median_filter(img, K_size=3) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
209
MIT
gasyori_100_knocks
メディアンフィルタ(3x3)を実装し、imori_noise.jpgのノイズを除去せよ。 メディアンフィルタとは画像の平滑化を行うフィルタの一種である。 これは注目画素の3x3の領域内の、メディアン値(中央値)を出力するフィルタである。 pythonを用いてこれをゼロパディングせよ。
import cv2 import numpy as np # mean filter def mean_filter(img, K_size=3): H, W, C = img.shape # zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=np.float) out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float) tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.mean(tmp[y: y + K_size, x: x + K_size, c]) out = out[pad: pad + H, pad: pad + W].astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg") # Mean Filter out = mean_filter(img, K_size=3) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
210
MIT
gasyori_100_knocks
pythonを用いて、平滑化フィルタ(3x3)を実装せよ。 平滑化フィルタはフィルタ内の画素の平均値を出力するフィルタである。
import cv2 import numpy as np # motion filter def motion_filter(img, K_size=3): H, W, C = img.shape # Kernel K = np.diag( [1] * K_size ).astype(np.float) K /= K_size # zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=np.float) out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float) tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.sum(K * tmp[y: y + K_size, x: x + K_size, c]) out = out[pad: pad + H, pad: pad + W].astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg") # motion filtering out = motion_filter(img, K_size=3) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
211
MIT
gasyori_100_knocks
pythonを用いて、モーションフィルタ(3x3)を実装せよ。 モーションフィルタとは対角方向の平均値を取るフィルタであり、次式で定義される。 1/3 0 0 [ 0 1/3 0 ] 0 0 1/3
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # max-min filter def max_min_filter(img, K_size=3): H, W, C = img.shape ## Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = gray.copy().astype(np.float) tmp = out.copy() # filtering for y in range(H): for x in range(W): out[pad + y, pad + x] = np.max(tmp[y: y + K_size, x: x + K_size]) - np.min(tmp[y: y + K_size, x: x + K_size]) out = out[pad: pad + H, pad: pad + W].astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float) # grayscale gray = BGR2GRAY(img) # Max-Min filtering out = max_min_filter(gray, K_size=3) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
212
MIT
gasyori_100_knocks
pythonを用いて、MAX-MINフィルタ(3x3)を実装せよ。 MAX-MINフィルタとはフィルタ内の画素の最大値と最小値の差を出力するフィルタであり、エッジ検出のフィルタの一つである。エッジ検出とは画像内の線を検出るすることであり、このような画像内の情報を抜き出す操作を特徴抽出と呼ぶ。エッジ検出では多くの場合、グレースケール画像に対してフィルタリングを行う。
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # different filter def different_filter(img, K_size=3): H, W, C = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = gray.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() # vertical kernel Kv = [[0., -1., 0.],[0., 1., 0.],[0., 0., 0.]] # horizontal kernel Kh = [[0., 0., 0.],[-1., 1., 0.], [0., 0., 0.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y: y + K_size, x: x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y: y + K_size, x: x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad: pad + H, pad: pad + W].astype(np.uint8) out_h = out_h[pad: pad + H, pad: pad + W].astype(np.uint8) return out_v, out_h # Read image img = cv2.imread("imori.jpg").astype(np.float) # grayscale gray = BGR2GRAY(img) # different filtering out_v, out_h = different_filter(gray, K_size=3) # Save result cv2.imwrite("out_v.jpg", out_v) cv2.imshow("result", out_v) cv2.waitKey(0) cv2.imwrite("out_h.jpg", out_h) cv2.imshow("result", out_h) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
213
MIT
gasyori_100_knocks
pythonを用いて、微分フィルタ(3x3)を実装せよ。 微分フィルタは輝度の急激な変化が起こっている部分のエッジを取り出すフィルタであり、隣り合う画素同士の差を取る。 (a)縦方向 (b)横方向 0 -1 0 0 0 0 K = [ 0 1 0 ] K = [ -1 1 0 ] 0 0 0 0 0 0
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # sobel filter def sobel_filter(img, K_size=3): if len(img.shape) == 3: H, W, C = img.shape else: img = np.expand_dims(img, axis=-1) H, W, C = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = gray.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() ## Sobel vertical Kv = [[1., 2., 1.],[0., 0., 0.], [-1., -2., -1.]] ## Sobel horizontal Kh = [[1., 0., -1.],[2., 0., -2.],[1., 0., -1.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y: y + K_size, x: x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y: y + K_size, x: x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad: pad + H, pad: pad + W].astype(np.uint8) out_h = out_h[pad: pad + H, pad: pad + W].astype(np.uint8) return out_v, out_h # Read image img = cv2.imread("imori.jpg").astype(np.float) # grayscale gray = BGR2GRAY(img) # sobel filtering out_v, out_h = sobel_filter(gray, K_size=3) # Save result cv2.imwrite("out_v.jpg", out_v) cv2.imshow("result", out_v) cv2.waitKey(0) cv2.imwrite("out_h.jpg", out_h) cv2.imshow("result", out_h) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
214
MIT
gasyori_100_knocks
pythonを用いて、Sobelフィルタ(3x3)を実装せよ。 ソーベルフィルタ(Sobelフィルタ)は特定方向(縦や横)のエッジのみを抽出するフィルタであり、次式でそれぞれ定義される。 (a)縦方向 (b)横方向 1 2 1 1 0 -1 K = [ 0 0 0 ] K = [ 2 0 -2 ] -1 -2 -1 1 0 -1
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # prewitt filter def prewitt_filter(img, K_size=3): H, W, C = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = gray.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() ## prewitt vertical kernel Kv = [[-1., -1., -1.],[0., 0., 0.], [1., 1., 1.]] ## prewitt horizontal kernel Kh = [[-1., 0., 1.],[-1., 0., 1.],[-1., 0., 1.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y: y + K_size, x: x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y: y + K_size, x: x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad: pad + H, pad: pad + W].astype(np.uint8) out_h = out_h[pad: pad + H, pad: pad + W].astype(np.uint8) return out_v, out_h # Read image img = cv2.imread("imori.jpg").astype(np.float) # grayscale gray = BGR2GRAY(img) # prewitt filtering out_v, out_h = prewitt_filter(gray, K_size=3) # Save result cv2.imwrite("out_v.jpg", out_v) cv2.imshow("result", out_v) cv2.waitKey(0) cv2.imwrite("out_h.jpg", out_h) cv2.imshow("result", out_h) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
215
MIT
gasyori_100_knocks
pythonを用いて、Prewittフィルタ(3x3)を実装せよ。 Prewittフィルタはエッジ抽出フィルタの一種であり、次式で定義される。 (a)縦方向 (b)横方向 -1 -1 -1 -1 0 1 K = [ 0 0 0 ] K = [ -1 0 1 ] 1 1 1 -1 0 1
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # laplacian filter def laplacian_filter(img, K_size=3): H, W, C = img.shape # zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = gray.copy().astype(np.float) tmp = out.copy() # laplacian kernle K = [[0., 1., 0.],[1., -4., 1.], [0., 1., 0.]] # filtering for y in range(H): for x in range(W): out[pad + y, pad + x] = np.sum(K * (tmp[y: y + K_size, x: x + K_size])) out = np.clip(out, 0, 255) out = out[pad: pad + H, pad: pad + W].astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float) # grayscale gray = BGR2GRAY(img) # prewitt filtering out = laplacian_filter(gray, K_size=3) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
216
MIT
gasyori_100_knocks
pythonを用いて、Laplacianフィルタを実装せよ。 Laplacian(ラプラシアン)フィルタとは輝度の二次微分をとることでエッジ検出を行うフィルタである。 デジタル画像は離散データであるので、x方向・y方向の一次微分は、それぞれ次式で表される。 Ix(x,y) = (I(x+1, y) - I(x,y)) / ((x+1)-x) = I(x+1, y) - I(x,y) Iy(x,y) = (I(x, y+1) - I(x,y)) / ((y+1)-y) = I(x, y+1) - I(x,y) さらに二次微分は、次式で表される。 Ixx(x,y) = (Ix(x,y) - Ix(x-1,y)) / ((x+1)-x) = Ix(x,y) - Ix(x-1,y) = (I(x+1, y) - I(x,y)) - (I(x, y) - I(x-1,y)) = I(x+1,y) - 2 * I(x,y) + I(x-1,y) Iyy(x,y) = ... = I(x,y+1) - 2 * I(x,y) + I(x,y-1) これらより、ラプラシアン は次式で定義される。 D^2 I(x,y) = Ixx(x,y) + Iyy(x,y) = I(x-1,y) + I(x,y-1) - 4 * I(x,y) + I(x+1,y) + I(x,y+1) これをカーネル化すると、次のようになる。 0 1 0 K = [ 1 -4 1 ] 0 1 0
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # emboss filter def emboss_filter(img, K_size=3): H, W, C = img.shape # zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = gray.copy().astype(np.float) tmp = out.copy() # emboss kernel K = [[-2., -1., 0.],[-1., 1., 1.], [0., 1., 2.]] # filtering for y in range(H): for x in range(W): out[pad + y, pad + x] = np.sum(K * (tmp[y: y + K_size, x: x + K_size])) out = np.clip(out, 0, 255) out = out[pad: pad + H, pad: pad + W].astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float) # grayscale gray = BGR2GRAY(img) # emboss filtering out = emboss_filter(gray, K_size=3) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
217
MIT
gasyori_100_knocks
pythonを用いて、Embossフィルタを実装せよ。 Embossフィルタとは輪郭部分を浮き出しにするフィルタで、次式で定義される。 -2 -1 0 K = [ -1 1 1 ] 0 1 2
import cv2 import numpy as np # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # LoG filter def LoG_filter(img, K_size=5, sigma=3): H, W, C = img.shape # zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = gray.copy().astype(np.float) tmp = out.copy() # LoG Kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(-pad, -pad + K_size): for y in range(-pad, -pad + K_size): K[y + pad, x + pad] = (x ** 2 + y ** 2 - sigma ** 2) * np.exp( -(x ** 2 + y ** 2) / (2 * (sigma ** 2))) K /= (2 * np.pi * (sigma ** 6)) K /= K.sum() # filtering for y in range(H): for x in range(W): out[pad + y, pad + x] = np.sum(K * tmp[y: y + K_size, x: x + K_size]) out = np.clip(out, 0, 255) out = out[pad: pad + H, pad: pad + W].astype(np.uint8) return out # Read image img = cv2.imread("imori_noise.jpg") # grayscale gray = BGR2GRAY(img) # LoG filtering out = LoG_filter(gray, K_size=5, sigma=3) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
218
MIT
gasyori_100_knocks
pythonを用いて、LoGフィルタ(sigma=3、カーネルサイズ=5)を実装し、imori_noise.jpgのエッジを検出せよ。 LoGフィルタとはLaplacian of Gaussianであり、ガウシアンフィルタで画像を平滑化した後にラプラシアンフィルタで輪郭を取り出すフィルタである。 Laplcianフィルタは二次微分をとるのでノイズが強調されるのを防ぐために、予めGaussianフィルタでノイズを抑える。 LoGフィルタは次式で定義される。 LoG(x,y) = (x^2 + y^2 - sigma^2) / (2 * pi * sigma^6) * exp(-(x^2+y^2) / (2*sigma^2))
import cv2 import numpy as np import matplotlib.pyplot as plt # Read image img = cv2.imread("imori_dark.jpg").astype(np.float) # Display histogram plt.hist(img.ravel(), bins=255, rwidth=0.8, range=(0, 255)) plt.savefig("out.png") plt.show()
code_generation
219
MIT
gasyori_100_knocks
pythonを用いて、matplotlibを用いてimori_dark.jpgのヒストグラムを表示せよ。 ヒストグラムとは画素の出現回数をグラフにしたものである。 matplotlibではhist()という関数がすでにあるので、それを利用する。
import cv2 import numpy as np import matplotlib.pyplot as plt # histogram normalization def hist_normalization(img, a=0, b=255): # get max and min c = img.min() d = img.max() out = img.copy() # normalization out = (b-a) / (d - c) * (out - c) + a out[out < a] = a out[out > b] = b out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori_dark.jpg").astype(np.float) H, W, C = img.shape # histogram normalization out = hist_normalization(img) # Display histogram plt.hist(out.ravel(), bins=255, rwidth=0.8, range=(0, 255)) plt.savefig("out_his.png") plt.show() # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
220
MIT
gasyori_100_knocks
pythonを用いて、ヒストグラム正規化を実装せよ。 ヒストグラムは偏りを持っていることが伺える。 例えば、0に近い画素が多ければ画像は全体的に暗く、255に近い画素が多ければ画像は明るくなる。 ヒストグラムが局所的に偏っていることをダイナミックレンジが狭いなどと表現する。 そのため画像を人の目に見やすくするために、ヒストグラムを正規化したり平坦化したりなどの処理が必要である。 このヒストグラム正規化は濃度階調変換(gray-scale transformation) と呼ばれ、[c,d]の画素値を持つ画像を[a,b]のレンジに変換する場合は次式で実現できる。 今回はimori_dark.jpgを[0, 255]のレンジにそれぞれ変換する。
import cv2 import numpy as np import matplotlib.pyplot as plt # histogram manipulation def hist_mani(img, m0=128, s0=52): m = np.mean(img) s = np.std(img) out = img.copy() # normalize out = s0 / s * (out - m) + m0 out[out < 0] = 0 out[out > 255] = 255 out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori_dark.jpg").astype(np.float) out = hist_mani(img) # Display histogram plt.hist(out.ravel(), bins=255, rwidth=0.8, range=(0, 255)) plt.savefig("out_his.png") plt.show() # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
221
MIT
gasyori_100_knocks
pythonを用いて、ヒストグラムの平均値をm0=128、標準偏差をs0=52になるように操作せよ。 これはヒストグラムのダイナミックレンジを変更するのではなく、ヒストグラムを平坦に変更する操作である。 平均値m、標準偏差s、のヒストグラムを平均値m0, 標準偏差s0に変更するには、次式によって変換する。 xout = s0 / s * (xin - m) + m0
import cv2 import numpy as np import matplotlib.pyplot as plt # histogram equalization def hist_equal(img, z_max=255): H, W, C = img.shape S = H * W * C * 1. out = img.copy() sum_h = 0. for i in range(1, 255): ind = np.where(img == i) sum_h += len(img[ind]) z_prime = z_max / S * sum_h out[ind] = z_prime out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float) # histogram normalization out = hist_equal(img) # Display histogram plt.hist(out.ravel(), bins=255, rwidth=0.8, range=(0, 255)) plt.savefig("out_his.png") plt.show() # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
222
MIT
gasyori_100_knocks
pythonを用いて、ヒストグラム平坦化を実装せよ。 ヒストグラム平坦化とはヒストグラムを平坦に変更する操作であり、上記の平均値や標準偏差などを必要とせず、ヒストグラム値を均衡にする操作である。 これは次式で定義される。 ただし、S ... 画素値の総数、Zmax ... 画素値の最大値、h(z) ... 濃度zの度数 Z' = Zmax / S * Sum{i=0:z} h(z)
mport cv2 import numpy as np import matplotlib.pyplot as plt # gamma correction def gamma_correction(img, c=1, g=2.2): out = img.copy() out /= 255. out = (1/c * out) ** (1/g) out *= 255 out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori_gamma.jpg").astype(np.float) # Gammma correction out = gamma_correction(img) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
223
MIT
gasyori_100_knocks
pythonを用いて、imori_gamma.jpgに対してガンマ補正(c=1, g=2.2)を実行せよ。 ガンマ補正とは、カメラなどの媒体の経由によって画素値が非線形的に変換された場合の補正である。ディスプレイなどで画像をそのまま表示すると画面が暗くなってしまうため、RGBの値を予め大きくすることで、ディスプレイの特性を排除した画像表示を行うことがガンマ補正の目的である。 非線形変換は次式で起こるとされる。 ただしxは[0,1]に正規化されている。 c ... 定数、g ... ガンマ特性(通常は2.2) x' = c * Iin ^ g
import cv2 import numpy as np import matplotlib.pyplot as plt # Nereset Neighbor interpolation def nn_interpolate(img, ax=1, ay=1): H, W, C = img.shape aH = int(ay * H) aW = int(ax * W) y = np.arange(aH).repeat(aW).reshape(aW, -1) x = np.tile(np.arange(aW), (aH, 1)) y = np.round(y / ay).astype(np.int) x = np.round(x / ax).astype(np.int) out = img[y,x] out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float) # Nearest Neighbor out = nn_interpolate(img, ax=1.5, ay=1.5) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
224
MIT
gasyori_100_knocks
pythonを用いて、最近傍補間により画像を1.5倍に拡大せよ。 最近傍補間(Nearest Neighbor)は画像の拡大時に最近傍にある画素をそのまま使う手法である。 シンプルで処理速度が速いが、画質の劣化は著しい。 次式で補間される。 I' ... 拡大後の画像、 I ... 拡大前の画像、a ... 拡大率、[ ] ... 四捨五入 I'(x,y) = I([x/a], [y/a])
import cv2 import numpy as np import matplotlib.pyplot as plt # Bi-Linear interpolation def bl_interpolate(img, ax=1., ay=1.): H, W, C = img.shape aH = int(ay * H) aW = int(ax * W) # get position of resized image y = np.arange(aH).repeat(aW).reshape(aW, -1) x = np.tile(np.arange(aW), (aH, 1)) # get position of original position y = (y / ay) x = (x / ax) ix = np.floor(x).astype(np.int) iy = np.floor(y).astype(np.int) ix = np.minimum(ix, W-2) iy = np.minimum(iy, H-2) # get distance dx = x - ix dy = y - iy dx = np.repeat(np.expand_dims(dx, axis=-1), 3, axis=-1) dy = np.repeat(np.expand_dims(dy, axis=-1), 3, axis=-1) # interpolation out = (1-dx) * (1-dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix+1] + (1 - dx) * dy * img[iy+1, ix] + dx * dy * img[iy+1, ix+1] out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float) # Bilinear interpolation out = bl_interpolate(img, ax=1.5, ay=1.5) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
225
MIT
gasyori_100_knocks
pythonを用いて、Bi-linear補間により画像を1.5倍に拡大せよ。 Bi-linear補間とは周辺の4画素に距離に応じた重みをつけることで補完する手法である。 計算量が多いだけ処理時間がかかるが、画質の劣化を抑えることができる。 1. 拡大画像の座標(x', y')を拡大率aで割り、floor(x'/a, y'/a)を求める。 2. 元画像の(x'/a, y'/a)の周囲4画素、I(x,y), I(x+1,y), I(x,y+1), I(x+1, y+1)を求める I(x,y) I(x+1,y) * (x'/a,y'/a) I(x,y+1) I(x+1,y+1) 3. それぞれの画素と(x'/a, y'/a)との距離dを求め、重み付けする。 w = d / Sum d 4. 次式によって拡大画像の画素(x',y')を求める。 dx = x'/a - x , dy = y'/a - y I'(x',y') = (1-dx)(1-dy)I(x,y) + dx(1-dy)I(x+1,y) + (1-dx)dyI(x,y+1) + dxdyI(x+1,y+1)
import cv2 import numpy as np import matplotlib.pyplot as plt # Bi-cubic interpolation def bc_interpolate(img, ax=1., ay=1.): H, W, C = img.shape aH = int(ay * H) aW = int(ax * W) # get positions of resized image y = np.arange(aH).repeat(aW).reshape(aW, -1) x = np.tile(np.arange(aW), (aH, 1)) y = (y / ay) x = (x / ax) # get positions of original image ix = np.floor(x).astype(np.int) iy = np.floor(y).astype(np.int) ix = np.minimum(ix, W-1) iy = np.minimum(iy, H-1) # get distance of each position of original image dx2 = x - ix dy2 = y - iy dx1 = dx2 + 1 dy1 = dy2 + 1 dx3 = 1 - dx2 dy3 = 1 - dy2 dx4 = 1 + dx3 dy4 = 1 + dy3 dxs = [dx1, dx2, dx3, dx4] dys = [dy1, dy2, dy3, dy4] # bi-cubic weight def weight(t): a = -1. at = np.abs(t) w = np.zeros_like(t) ind = np.where(at <= 1) w[ind] = ((a+2) * np.power(at, 3) - (a+3) * np.power(at, 2) + 1)[ind] ind = np.where((at > 1) & (at <= 2)) w[ind] = (a*np.power(at, 3) - 5*a*np.power(at, 2) + 8*a*at - 4*a)[ind] return w w_sum = np.zeros((aH, aW, C), dtype=np.float32) out = np.zeros((aH, aW, C), dtype=np.float32) # interpolate for j in range(-1, 3): for i in range(-1, 3): ind_x = np.minimum(np.maximum(ix + i, 0), W-1) ind_y = np.minimum(np.maximum(iy + j, 0), H-1) wx = weight(dxs[i+1]) wy = weight(dys[j+1]) wx = np.repeat(np.expand_dims(wx, axis=-1), 3, axis=-1) wy = np.repeat(np.expand_dims(wy, axis=-1), 3, axis=-1) w_sum += wx * wy out += wx * wy * img[ind_y, ind_x] out /= w_sum out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Bi-cubic interpolation out = bc_interpolate(img, ax=1.5, ay=1.5) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
226
MIT
gasyori_100_knocks
pythonを用いて、Bi-cubic補間により画像を1.5倍に拡大せよ。 Bi-cubic補間とはBi-linear補間の拡張であり、周辺の16画素から補間を行う。 I(x-1,y-1) I(x,y-1) I(x+1,y-1) I(x+2,y-1) I(x-1,y) I(x,y) I(x+1,y) I(x+2,y) I(x-1,y+1) I(x,y+1) I(x+1,y+1) I(x+2,y+1) I(x-1,y+2) I(x,y+2) I(x+1,y+2) I(x+2,y+2) それぞれの画素との距離は次式の様に決定される。 dx1 = x'/a - (x-1) , dx2 = x'/a - x , dx3 = (x+1) - x'/a , dx4 = (x+2) - x'/a dy1 = y'/a - (y-1) , dy2 = y'/a - y , dy3 = (y+1) - y'/a , dy4 = (y+2) - y'/a 重みは距離によって次の関数により決定される。 a は多くの場合-1をとる。だいたい図の青色のピクセルは距離|t|<=1、緑色が1<|t|<=2の重みとなる。 h(t) = { (a+2)|t|^3 - (a+3)|t|^2 + 1 (when |t|<=1) a|t|^3 - 5a|t|^2 + 8a|t| - 4a (when 1<|t|<=2) 0 (when 2<|t|) これら画素と重みを用いて、次式で拡大画像の画素が計算される。 それぞれの画素と重みを掛けた和を重みの和で割る。 I'(x', y') = (Sum{i=-1:2}{j=-1:2} I(x+i,y+j) * wxi * wyj) / Sum{i=-1:2}{j=-1:2} wxi * wyj
import cv2 import numpy as np import matplotlib.pyplot as plt # Affine def affine(img, a, b, c, d, tx, ty): H, W, C = img.shape # temporary image img = np.zeros((H+2, W+2, C), dtype=np.float32) img[1:H+1, 1:W+1] = _img # get new image shape H_new = np.round(H * d).astype(np.int) W_new = np.round(W * a).astype(np.int) out = np.zeros((H_new+1, W_new+1, C), dtype=np.float32) # get position of new image x_new = np.tile(np.arange(W_new), (H_new, 1)) y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1) # get position of original image by affine adbc = a * d - b * c x = np.round((d * x_new - b * y_new) / adbc).astype(np.int) - tx + 1 y = np.round((-c * x_new + a * y_new) / adbc).astype(np.int) - ty + 1 x = np.minimum(np.maximum(x, 0), W+1).astype(np.int) y = np.minimum(np.maximum(y, 0), H+1).astype(np.int) # assgin pixcel to new image out[y_new, x_new] = img[y, x] out = out[:H_new, :W_new] out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Affine out = affine(img, a=1, b=0, c=0, d=1, tx=30, ty=-30) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
227
MIT
gasyori_100_knocks
pythonを用いて、アフィン変換を利用して画像をx方向に+30、y方向に-30だけ平行移動させよ。 アフィン変換とは3x3の行列を用いて画像の変換を行う操作である。 変換は(1)平行移動(Q.28) (2)拡大縮小(Q.29) (3)回転(Q.30) (4)スキュー(Q.31) がある。 元画像を(x,y)、変換後の画像を(x',y')とする。 画像の拡大縮小は、次式で表される。 [ x' ] = [a b][x] y' c d y 一方、平行移動は次式となる。 [ x' ] = [x] + [tx] y' y + ty 以上を一つの式にまとめると、次式になり、これがアフィン変換である。 x' a b tx x [ y' ] = [ c d ty ][ y ] 1 0 0 1 1 しかし実装する時は、元画像に対して1ピクセルずつ行うと、処理後の画像で値が割り当てられない可能性がでてきてしまう。よって、処理後画像の各ピクセルに対してAffine変換の逆変換を行い、値をあ割り当てる元画像の座標を取得する必要がある。Affine変換の逆操作は次式となる。 今回の平行移動では次式を用いる。tx, tyが平行移動のピクセルの移動距離となる。 x' 1 0 tx x [ y' ] = [ 0 1 ty ][ y ] 1 0 0 1 1
import cv2 import numpy as np import matplotlib.pyplot as plt # Affine def affine(img, a, b, c, d, tx, ty): H, W, C = img.shape # temporary image img = np.zeros((H+2, W+2, C), dtype=np.float32) img[1:H+1, 1:W+1] = _img # get new image shape H_new = np.round(H * d).astype(np.int) W_new = np.round(W * a).astype(np.int) out = np.zeros((H_new+1, W_new+1, C), dtype=np.float32) # get position of new image x_new = np.tile(np.arange(W_new), (H_new, 1)) y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1) # get position of original image by affine adbc = a * d - b * c x = np.round((d * x_new - b * y_new) / adbc).astype(np.int) - tx + 1 y = np.round((-c * x_new + a * y_new) / adbc).astype(np.int) - ty + 1 x = np.minimum(np.maximum(x, 0), W+1).astype(np.int) y = np.minimum(np.maximum(y, 0), H+1).astype(np.int) # assgin pixcel to new image out[y_new, x_new] = img[y, x] out = out[:H_new, :W_new] out = out.astype(np.uint8) return out # Read image _img = cv2.imread("imori.jpg").astype(np.float32) # Affine out = affine(img, a=1.3, b=0, c=0, d=0.8, tx=30, ty=-30) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
228
MIT
gasyori_100_knocks
pythonを用いて、アフィン変換を用いて、(1)x方向に1.3倍、y方向に0.8倍にリサイズせよ。 また、(2) (1)の条件に加えて、x方向に+30、y方向に-30だけ平行移動を同時に実現せよ。
import cv2 import numpy as np import matplotlib.pyplot as plt # affine def affine(img, a, b, c, d, tx, ty): H, W, C = _img.shape # temporary image img = np.zeros((H+2, W+2, C), dtype=np.float32) img[1:H+1, 1:W+1] = _img # get shape of new image H_new = np.round(H).astype(np.int) W_new = np.round(W).astype(np.int) out = np.zeros((H_new, W_new, C), dtype=np.float32) # get position of new image x_new = np.tile(np.arange(W_new), (H_new, 1)) y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1) # get position of original image by affine adbc = a * d - b * c x = np.round((d * x_new - b * y_new) / adbc).astype(np.int) - tx + 1 y = np.round((-c * x_new + a * y_new) / adbc).astype(np.int) - ty + 1 # adjust center by affine dcx = (x.max() + x.min()) // 2 - W // 2 dcy = (y.max() + y.min()) // 2 - H // 2 x -= dcx y -= dcy x = np.clip(x, 0, W + 1) y = np.clip(y, 0, H + 1) # assign pixcel out[y_new, x_new] = img[y, x] out = out.astype(np.uint8) return out # Read image _img = cv2.imread("imori.jpg").astype(np.float32) # Affine A = 30. theta = - np.pi * A / 180. out = affine(img, a=np.cos(theta), b=-np.sin(theta), c=np.sin(theta), d=np.cos(theta), tx=0, ty=0) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
229
MIT
gasyori_100_knocks
pythonを用いて、 (1)アフィン変換を用いて、反時計方向に30度回転させよ。 (2) アフィン変換を用いて、反時計方向に30度回転した画像で中心座標を固定することで、なるべく黒い領域がなくなるように画像を作成せよ。 (ただし、単純なアフィン変換を行うと画像が切れてしまうので、工夫を要する。) アフィン変換において、反時計方向にA度回転させる時は、次式となる。 x' cosA -sinA tx x [ y' ] = [ sinA cosA ty ][ y ] 1 0 0 1 1
import cv2 import numpy as np import matplotlib.pyplot as plt # Affine def affine(img, dx=30, dy=30): # get shape H, W, C = img.shape # Affine hyper parameters a = 1. b = dx / H c = dy / W d = 1. tx = 0. ty = 0. # prepare temporary _img = np.zeros((H+2, W+2, C), dtype=np.float32) # insert image to center of temporary _img[1:H+1, 1:W+1] = img # prepare affine image temporary H_new = np.ceil(dy + H).astype(np.int) W_new = np.ceil(dx + W).astype(np.int) out = np.zeros((H_new, W_new, C), dtype=np.float32) # preprare assigned index x_new = np.tile(np.arange(W_new), (H_new, 1)) y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1) # prepare inverse matrix for affine adbc = a * d - b * c x = np.round((d * x_new - b * y_new) / adbc).astype(np.int) - tx + 1 y = np.round((-c * x_new + a * y_new) / adbc).astype(np.int) - ty + 1 x = np.minimum(np.maximum(x, 0), W+1).astype(np.int) y = np.minimum(np.maximum(y, 0), H+1).astype(np.int) # assign value from original to affine image out[y_new, x_new] = _img[y, x] out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Affine out = affine(img, dx=30, dy=30) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
230
MIT
gasyori_100_knocks
pythonを用いて、 (1)アフィン変換を用いて、出力(1)のようなX-sharing(dx = 30)画像を作成せよ。 (2)アフィン変換を用いて、出力2のようなY-sharing(dy = 30)画像を作成せよ。 (3)アフィン変換を用いて、出力3のような幾何変換した(dx = 30, dy = 30)画像を作成せよ。 このような画像はスキュー画像と呼ばれ、画像を斜め方向に伸ばした画像である。 出力(1)の場合、x方向にdxだけ引き伸ばした画像はX-sharingと呼ばれる。 出力(2)の場合、y方向にdyだけ引き伸ばした画像はY-sharingと呼ばれる。 それぞれ次式のアフィン変換で実現できる。 ただし、元画像のサイズがh x wとする。 (1) X-sharing a = dx / h x' 1 a tx x [ y' ] = [ 0 1 ty ][ y ] 1 0 0 1 1 (2) Y-sharing a = dy / w x' 1 0 tx x [ y' ] = [ a 1 ty ][ y ] 1 0 0 1 1
import cv2 import numpy as np import matplotlib.pyplot as plt # DFT hyper-parameters K, L = 128, 128 channel = 3 # DFT def dft(img): H, W, _ = img.shape # Prepare DFT coefficient G = np.zeros((L, K, channel), dtype=np.complex) # prepare processed index corresponding to original image positions x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # dft for c in range(channel): for l in range(L): for k in range(K): G[l, k, c] = np.sum(img[..., c] * np.exp(-2j * np.pi * (x * k / K + y * l / L))) / np.sqrt(K * L) #for n in range(N): # for m in range(M): # v += gray[n, m] * np.exp(-2j * np.pi * (m * k / M + n * l / N)) #G[l, k] = v / np.sqrt(M * N) return G # IDFT def idft(G): # prepare out image H, W, _ = G.shape out = np.zeros((H, W, channel), dtype=np.float32) # prepare processed index corresponding to original image positions x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # idft for c in range(channel): for l in range(H): for k in range(W): out[l, k, c] = np.abs(np.sum(G[..., c] * np.exp(2j * np.pi * (x * k / W + y * l / H)))) / np.sqrt(W * H) # clipping out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # DFT G = dft(img) # write poser spectal to image ps = (np.abs(G) / np.abs(G).max() * 255).astype(np.uint8) cv2.imwrite("out_ps.jpg", ps) # IDFT out = idft(G) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out) """ fimg = np.fft.fft2(gray) # 第1象限と第3象限, 第2象限と第4象限を入れ替え fimg = np.fft.fftshift(fimg) print(fimg.shape) # パワースペクトルの計算 mag = 20*np.log(np.abs(fimg)) # 入力画像とスペクトル画像をグラフ描画 plt.subplot(121) plt.imshow(gray, cmap = 'gray') plt.subplot(122) plt.imshow(mag, cmap = 'gray') plt.show() """
code_generation
231
MIT
gasyori_100_knocks
pythonを用いて、二次元離散フーリエ変換(DFT)を実装し、imori.jpgをグレースケール化したものの周波数のパワースペクトルを表示せよ。 また、逆二次元離散フーリエ変換(IDFT)で画像を復元せよ。 二次元離散フーリエ変換(DFT: Discrete Fourier Transformation)とはフーリエ変換の画像に対する処理方法である。 通常のフーリエ変換はアナログ信号や音声などの連続値かつ一次元を対象に周波数成分を求める計算処理である。 一方、ディジタル画像は[0,255]の離散値をとり、かつ画像はHxWの二次元表示であるので、二次元離散フーリエ変換が行われる。 二次元離散フーリエ変換(DFT)は次式で計算される。 K = 0:W, l = 0:H, 入力画像をI として G(k,l) = Sum_{y=0:H-1, x=0:W-1} I(x,y) exp( -2pi * j * (kx/W + ly/H)) / sqrt(H * W) K = [0, W-1], l = [0, H-1], 入力画像を I として ここでは画像をグレースケール化してから二次元離散フーリエ変換を行え。 パワースペクトルとは Gは複素数で表されるので、Gの絶対値を求めることである。 今回のみ画像表示の時はパワースペクトルは[0,255]にスケーリングせよ。 逆二次元離散フーリエ変換(IDFT: Inverse DFT)とは周波数成分Gから元の画像を復元する手法であり、次式で定義される。 x = 0:W, y = 0:H として I(x,y) = Sum_{l=0:H-1, k=0:W-1} G(k,l) exp( 2pi * j * (kx/W + ly/H)) / sqrt(H * W) x = [0, W-1], y = [0, H-1] として 上が定義式ですがexp(j)は複素数の値をとってしまうので、実際にコードにするときはぜ下式のように絶対値を使います。 シンプルに全部for文で回すと128^4の計算になるので、時間がかかってしまいます。numpyをうまく活用すれば計算コストを減らすことができます。(解答は128^2まで減らしました。)
import cv2 import numpy as np import matplotlib.pyplot as plt # DFT hyper-parameters K, L = 128, 128 channel = 3 # bgr -> gray def bgr2gray(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # DFT def dft(img): # Prepare DFT coefficient G = np.zeros((L, K, channel), dtype=np.complex) # prepare processed index corresponding to original image positions x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # dft for c in range(channel): for l in range(L): for k in range(K): G[l, k, c] = np.sum(img[..., c] * np.exp(-2j * np.pi * (x * k / K + y * l / L))) / np.sqrt(K * L) #for n in range(N): # for m in range(M): # v += gray[n, m] * np.exp(-2j * np.pi * (m * k / M + n * l / N)) #G[l, k] = v / np.sqrt(M * N) return G # IDFT def idft(G): # prepare out image H, W, _ = G.shape out = np.zeros((H, W, channel), dtype=np.float32) # prepare processed index corresponding to original image positions x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # idft for c in range(channel): for l in range(H): for k in range(W): out[l, k, c] = np.abs(np.sum(G[..., c] * np.exp(2j * np.pi * (x * k / W + y * l / H)))) / np.sqrt(W * H) # clipping out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # LPF def lpf(G, ratio=0.5): H, W, _ = G.shape # transfer positions _G = np.zeros_like(G) _G[:H//2, :W//2] = G[H//2:, W//2:] _G[:H//2, W//2:] = G[H//2:, :W//2] _G[H//2:, :W//2] = G[:H//2, W//2:] _G[H//2:, W//2:] = G[:H//2, :W//2] # get distance from center (H / 2, W / 2) x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # make filter _x = x - W // 2 _y = y - H // 2 r = np.sqrt(_x ** 2 + _y ** 2) mask = np.ones((H, W), dtype=np.float32) mask[r > (W // 2 * ratio)] = 0 mask = np.repeat(mask, channel).reshape(H, W, channel) # filtering _G *= mask # reverse original positions G[:H//2, :W//2] = _G[H//2:, W//2:] G[:H//2, W//2:] = _G[H//2:, :W//2] G[H//2:, :W//2] = _G[:H//2, W//2:] G[H//2:, W//2:] = _G[:H//2, :W//2] return G # Read image img = cv2.imread("imori.jpg").astype(np.float32) H, W, C = img.shape # Gray scale gray = bgr2gray(img) # DFT G = dft(img) # LPF G = lpf(G) # IDFT out = idft(G) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
232
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgをグレースケール化したものをDFTし、ローパスフィルタを通してIDFTで画像を復元せよ。 DFTによって得られた周波数成分は左上、右上、左下、右下に近いほど低周波数の成分を含んでいることになり、中心に近いほど高周波成分を示す。 ![](assets/lpf.png) 画像における高周波成分とは色が変わっている部分(ノイズや輪郭など)を示し、低周波成分とは色があまり変わっていない部分(夕日のグラデーションなど)を表す。 ここでは、高周波成分をカットし、低周波成分のみを通すローパスフィルタを実装せよ。 ここでは低周波数の中心から高周波までの距離をrとすると0.5rまでの成分を通すとする。
import cv2 import numpy as np import matplotlib.pyplot as plt # DFT hyper-parameters K, L = 128, 128 channel = 3 # bgr -> gray def bgr2gray(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # DFT def dft(img): # Prepare DFT coefficient G = np.zeros((L, K, channel), dtype=np.complex) # prepare processed index corresponding to original image positions x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # dft for c in range(channel): for l in range(L): for k in range(K): G[l, k, c] = np.sum(img[..., c] * np.exp(-2j * np.pi * (x * k / K + y * l / L))) / np.sqrt(K * L) #for n in range(N): # for m in range(M): # v += gray[n, m] * np.exp(-2j * np.pi * (m * k / M + n * l / N)) #G[l, k] = v / np.sqrt(M * N) return G # IDFT def idft(G): # prepare out image H, W, _ = G.shape out = np.zeros((H, W, channel), dtype=np.float32) # prepare processed index corresponding to original image positions x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # idft for c in range(channel): for l in range(H): for k in range(W): out[l, k, c] = np.abs(np.sum(G[..., c] * np.exp(2j * np.pi * (x * k / W + y * l / H)))) / np.sqrt(W * H) # clipping out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # HPF def hpf(G, ratio=0.1): H, W, _ = G.shape # transfer positions _G = np.zeros_like(G) _G[:H//2, :W//2] = G[H//2:, W//2:] _G[:H//2, W//2:] = G[H//2:, :W//2] _G[H//2:, :W//2] = G[:H//2, W//2:] _G[H//2:, W//2:] = G[:H//2, :W//2] # get distance from center (H / 2, W / 2) x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # make filter _x = x - W // 2 _y = y - H // 2 r = np.sqrt(_x ** 2 + _y ** 2) mask = np.ones((H, W), dtype=np.float32) mask[r < (W // 2 * ratio)] = 0 mask = np.repeat(mask, channel).reshape(H, W, channel) # filtering _G *= mask # reverse original positions G[:H//2, :W//2] = _G[H//2:, W//2:] G[:H//2, W//2:] = _G[H//2:, :W//2] G[H//2:, :W//2] = _G[:H//2, W//2:] G[H//2:, W//2:] = _G[:H//2, :W//2] return G # Read image img = cv2.imread("imori.jpg").astype(np.float32) H, W, C = img.shape # Gray scale gray = bgr2gray(img) # DFT G = dft(img) # HPF G = hpf(G) # IDFT out = idft(G) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
233
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgをグレースケール化したものをDFTし、ハイパスフィルタを通してIDFTで画像を復元せよ。 ここでは、低周波成分をカットし、高周波成分のみを通すハイパスフィルタを実装せよ。 ここでは低周波数の中心から高周波までの距離をrとすると0.1rからの成分を通すとする。
import cv2 import numpy as np import matplotlib.pyplot as plt # DFT hyper-parameters K, L = 128, 128 channel = 3 # bgr -> gray def bgr2gray(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # DFT def dft(img): # Prepare DFT coefficient G = np.zeros((L, K, channel), dtype=np.complex) # prepare processed index corresponding to original image positions x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # dft for c in range(channel): for l in range(L): for k in range(K): G[l, k, c] = np.sum(img[..., c] * np.exp(-2j * np.pi * (x * k / K + y * l / L))) / np.sqrt(K * L) #for n in range(N): # for m in range(M): # v += gray[n, m] * np.exp(-2j * np.pi * (m * k / M + n * l / N)) #G[l, k] = v / np.sqrt(M * N) return G # IDFT def idft(G): # prepare out image H, W, _ = G.shape out = np.zeros((H, W, channel), dtype=np.float32) # prepare processed index corresponding to original image positions x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # idft for c in range(channel): for l in range(H): for k in range(W): out[l, k, c] = np.abs(np.sum(G[..., c] * np.exp(2j * np.pi * (x * k / W + y * l / H)))) / np.sqrt(W * H) # clipping out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # BPF def bpf(G, ratio1=0.1, ratio2=0.5): H, W, _ = G.shape # transfer positions _G = np.zeros_like(G) _G[:H//2, :W//2] = G[H//2:, W//2:] _G[:H//2, W//2:] = G[H//2:, :W//2] _G[H//2:, :W//2] = G[:H//2, W//2:] _G[H//2:, W//2:] = G[:H//2, :W//2] # get distance from center (H / 2, W / 2) x = np.tile(np.arange(W), (H, 1)) y = np.arange(H).repeat(W).reshape(H, -1) # make filter _x = x - W // 2 _y = y - H // 2 r = np.sqrt(_x ** 2 + _y ** 2) mask = np.ones((H, W), dtype=np.float32) mask[(r < (W // 2 * ratio1)) | (r > (W // 2 * ratio2))] = 0 mask = np.repeat(mask, channel).reshape(H, W, channel) # filtering _G *= mask # reverse original positions G[:H//2, :W//2] = _G[H//2:, W//2:] G[:H//2, W//2:] = _G[H//2:, :W//2] G[H//2:, :W//2] = _G[:H//2, W//2:] G[H//2:, W//2:] = _G[:H//2, :W//2] return G # Read image img = cv2.imread("imori.jpg").astype(np.float32) H, W, C = img.shape # Gray scale gray = bgr2gray(img) # DFT G = dft(img) # BPF G = bpf(G, ratio1=0.1, ratio2=0.5) # IDFT out = idft(G) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
234
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgをグレースケール化したものをDFTし、ハイパスフィルタを通してIDFTで画像を復元せよ。 ここでは、低周波成分と高周波成分の中間の周波数成分のみを通すハイパスフィルタを実装せよ。 ここでは低周波数の中心から高周波までの距離をrとすると0.1rから0.5rまでの成分を通すとする。
import cv2 import numpy as np import matplotlib.pyplot as plt # DCT hyoer-parameter T = 8 K = 8 channel = 3 # DCT weight def w(x, y, u, v): cu = 1. cv = 1. if u == 0: cu /= np.sqrt(2) if v == 0: cv /= np.sqrt(2) theta = np.pi / (2 * T) return (( 2 * cu * cv / T) * np.cos((2*x+1)*u*theta) * np.cos((2*y+1)*v*theta)) # DCT def dct(img): H, W, _ = img.shape F = np.zeros((H, W, channel), dtype=np.float32) for c in range(channel): for yi in range(0, H, T): for xi in range(0, W, T): for v in range(T): for u in range(T): for y in range(T): for x in range(T): F[v+yi, u+xi, c] += img[y+yi, x+xi, c] * w(x,y,u,v) return F # IDCT def idct(F): H, W, _ = F.shape out = np.zeros((H, W, channel), dtype=np.float32) for c in range(channel): for yi in range(0, H, T): for xi in range(0, W, T): for y in range(T): for x in range(T): for v in range(K): for u in range(K): out[y+yi, x+xi, c] += F[v+yi, u+xi, c] * w(x,y,u,v) out = np.clip(out, 0, 255) out = np.round(out).astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # DCT F = dct(img) # IDCT out = idct(F) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
235
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgをグレースケール化し離散コサイン変換を行い、逆離散コサイン変換を行え。 離散コサイン変換(DCT: Discrete Cosine Transformation)とは、次式で定義される周波数変換の一つである。 T = 8 F(u,v) = 2 / T * C(u)C(v) * Sum_{y=0:T-1} Sum_{x=0:T-1} f(x,y) cos((2x+1)u*pi/2T) cos((2y+1)v*pi/2T) 逆離散コサイン変換(IDCT: Inverse Discrete Cosine Transformation)とは離散コサイン変換の逆(復号)であり、次式で定義される。 ここでいう K は復元時にどれだけ解像度を良くするかを決定するパラメータである。 K = Tの時は、DCT係数を全部使うのでIDCT後の解像度は最大になるが、Kが1や2などの時は復元に使う情報量(DCT係数)が減るので解像度が下がる。これを適度に設定することで、画像の容量を減らすことができる。 T = 8 K = 8 f(x,y) = 2 / T * C(x)C(y) * Sum_{u=0:K-1} Sum_{v=0:K-1} F(u,v) cos((2x+1)u*pi/2T) cos((2y+1)v*pi/2T) ここでは画像を8x8ずつの領域に分割して、各領域で以上のDCT, IDCTを繰り返すことで、jpeg符号に応用される。 今回も同様に8x8の領域に分割して、DCT, IDCTを行え。
import cv2 import numpy as np import matplotlib.pyplot as plt # DCT hyoer-parameter T = 8 K = 4 channel = 3 # DCT weight def w(x, y, u, v): cu = 1. cv = 1. if u == 0: cu /= np.sqrt(2) if v == 0: cv /= np.sqrt(2) theta = np.pi / (2 * T) return (( 2 * cu * cv / T) * np.cos((2*x+1)*u*theta) * np.cos((2*y+1)*v*theta)) # DCT def dct(img): H, W, _ = img.shape F = np.zeros((H, W, channel), dtype=np.float32) for c in range(channel): for yi in range(0, H, T): for xi in range(0, W, T): for v in range(T): for u in range(T): for y in range(T): for x in range(T): F[v+yi, u+xi, c] += img[y+yi, x+xi, c] * w(x,y,u,v) return F # IDCT def idct(F): H, W, _ = F.shape out = np.zeros((H, W, channel), dtype=np.float32) for c in range(channel): for yi in range(0, H, T): for xi in range(0, W, T): for y in range(T): for x in range(T): for v in range(K): for u in range(K): out[y+yi, x+xi, c] += F[v+yi, u+xi, c] * w(x,y,u,v) out = np.clip(out, 0, 255) out = np.round(out).astype(np.uint8) return out # MSE def MSE(img1, img2): H, W, _ = img1.shape mse = np.sum((img1 - img2) ** 2) / (H * W * channel) return mse # PSNR def PSNR(mse, vmax=255): return 10 * np.log10(vmax * vmax / mse) # bitrate def BITRATE(): return 1. * T * K * K / T / T # Read image img = cv2.imread("imori.jpg").astype(np.float32) # DCT F = dct(img) # IDCT out = idct(F) # MSE mse = MSE(img, out) # PSNR psnr = PSNR(mse) # bitrate bitrate = BITRATE() print("MSE:", mse) print("PSNR:", psnr) print("bitrate:", bitrate) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
236
MIT
gasyori_100_knocks
pythonを用いて、IDCTで用いるDCT係数を8でなく、4にすると画像の劣化が生じる。 入力画像とIDCT画像のPSNRを求めよ。また、IDCTによるビットレートを求めよ。 PSNR(Peak Signal to Noise Ratio)とは信号対雑音比と呼ばれ、画像がどれだけ劣化したかを示す。 PSNRが大きいほど、画像が劣化していないことを示し、次式で定義される。 MAXは取りうる値の最大値で[0,255]の表示なら MAX=255 となる。 また、MSEはMean Squared Error(平均二乗誤差)と呼ばれ、二つの画像の差分の二乗の平均値を示す。 PSNR = 10 * log10(MAX^2 / MSE) MSE = Sum_{y=0:H-1} Sum_{x=0:W-1} (I1(x,y) - I2(x,y))^2 / (HW) ビットレートとは8x8でDCTを行い、IDCTでKxKの係数までを用いた時に次式で定義される。 bitrate = 8 * K^2 / 8^2
import cv2 import numpy as np import matplotlib.pyplot as plt # DCT hyoer-parameter T = 8 K = 4 channel = 3 # DCT weight def DCT_w(x, y, u, v): cu = 1. cv = 1. if u == 0: cu /= np.sqrt(2) if v == 0: cv /= np.sqrt(2) theta = np.pi / (2 * T) return (( 2 * cu * cv / T) * np.cos((2*x+1)*u*theta) * np.cos((2*y+1)*v*theta)) # DCT def dct(img): H, W, _ = img.shape F = np.zeros((H, W, channel), dtype=np.float32) for c in range(channel): for yi in range(0, H, T): for xi in range(0, W, T): for v in range(T): for u in range(T): for y in range(T): for x in range(T): F[v+yi, u+xi, c] += img[y+yi, x+xi, c] * DCT_w(x,y,u,v) return F # IDCT def idct(F): H, W, _ = F.shape out = np.zeros((H, W, channel), dtype=np.float32) for c in range(channel): for yi in range(0, H, T): for xi in range(0, W, T): for y in range(T): for x in range(T): for v in range(K): for u in range(K): out[y+yi, x+xi, c] += F[v+yi, u+xi, c] * DCT_w(x,y,u,v) out = np.clip(out, 0, 255) out = np.round(out).astype(np.uint8) return out # Quantization def quantization(F): H, W, _ = F.shape Q = np.array(((16, 11, 10, 16, 24, 40, 51, 61), (12, 12, 14, 19, 26, 58, 60, 55), (14, 13, 16, 24, 40, 57, 69, 56), (14, 17, 22, 29, 51, 87, 80, 62), (18, 22, 37, 56, 68, 109, 103, 77), (24, 35, 55, 64, 81, 104, 113, 92), (49, 64, 78, 87, 103, 121, 120, 101), (72, 92, 95, 98, 112, 100, 103, 99)), dtype=np.float32) for ys in range(0, H, T): for xs in range(0, W, T): for c in range(channel): F[ys: ys + T, xs: xs + T, c] = np.round(F[ys: ys + T, xs: xs + T, c] / Q) * Q return F # MSE def MSE(img1, img2): H, W, _ = img1.shape mse = np.sum((img1 - img2) ** 2) / (H * W * channel) return mse # PSNR def PSNR(mse, vmax=255): return 10 * np.log10(vmax * vmax / mse) # bitrate def BITRATE(): return 1. * T * K * K / T / T # Read image img = cv2.imread("imori.jpg").astype(np.float32) # DCT F = dct(img) # quantization F = quantization(F) # IDCT out = idct(F) # MSE mse = MSE(img, out) # PSNR psnr = PSNR(mse) # bitrate bitrate = BITRATE() print("MSE:", mse) print("PSNR:", psnr) print("bitrate:", bitrate) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
237
MIT
gasyori_100_knocks
pythonを用いて、DCT係数を量子化し、IDCTで復元せよ。また、その時の画像の容量を比べよ。 DCT係数を量子化することはjpeg画像にする符号化で用いられる手法である。 量子化とは、値を予め決定された区分毎に値を大まかに丸め込む作業であり、floorやceil, roundなどが似た計算である。 JPEG画像ではDCT係数を下記で表される量子化テーブルに則って量子化する。 この量子化テーブルはjpeg団体の仕様書から取った。 量子化では8x8の係数をQで割り、四捨五入する。その後Qを掛けることで行われる。 IDCTでは係数は全て用いるものとする。 Q = np.array(((16, 11, 10, 16, 24, 40, 51, 61), (12, 12, 14, 19, 26, 58, 60, 55), (14, 13, 16, 24, 40, 57, 69, 56), (14, 17, 22, 29, 51, 87, 80, 62), (18, 22, 37, 56, 68, 109, 103, 77), (24, 35, 55, 64, 81, 104, 113, 92), (49, 64, 78, 87, 103, 121, 120, 101), (72, 92, 95, 98, 112, 100, 103, 99)), dtype=np.float32) 量子化を行うと画像の容量が減っていることから、データ量が削減されたことが伺える。
import cv2 import numpy as np import matplotlib.pyplot as plt channel = 3 # BGR -> Y Cb Cr def BGR2YCbCr(img): H, W, _ = img.shape ycbcr = np.zeros([H, W, 3], dtype=np.float32) ycbcr[..., 0] = 0.2990 * img[..., 2] + 0.5870 * img[..., 1] + 0.1140 * img[..., 0] ycbcr[..., 1] = -0.1687 * img[..., 2] - 0.3313 * img[..., 1] + 0.5 * img[..., 0] + 128. ycbcr[..., 2] = 0.5 * img[..., 2] - 0.4187 * img[..., 1] - 0.0813 * img[..., 0] + 128. return ycbcr # Y Cb Cr -> BGR def YCbCr2BGR(ycbcr): H, W, _ = ycbcr.shape out = np.zeros([H, W, channel], dtype=np.float32) out[..., 2] = ycbcr[..., 0] + (ycbcr[..., 2] - 128.) * 1.4020 out[..., 1] = ycbcr[..., 0] - (ycbcr[..., 1] - 128.) * 0.3441 - (ycbcr[..., 2] - 128.) * 0.7139 out[..., 0] = ycbcr[..., 0] + (ycbcr[..., 1] - 128.) * 1.7718 out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # bgr -> Y Cb Cr ycbcr = BGR2YCbCr(img) # process ycbcr[..., 0] *= 0.7 # YCbCr > RGB out = YCbCr2BGR(ycbcr) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
238
MIT
gasyori_100_knocks
pythonを用いて、YCbCr表色形において、Yを0.7倍してコントラストを暗くせよ。 YCbCr表色系とは、画像を明るさを表すY、輝度と青レベルの差Cb、輝度と赤レベルの差Crに分解する表現方法である。 これはJPEG変換で用いられる。 RGBからYCbCrへの変換は次式。 Y = 0.299 * R + 0.5870 * G + 0.114 * B Cb = -0.1687 * R - 0.3313 * G + 0.5 * B + 128 Cr = 0.5 * R - 0.4187 * G - 0.0813 * B + 128 YCbCrからRGBへの変換は次式。 R = Y + (Cr - 128) * 1.402 G = Y - (Cb - 128) * 0.3441 - (Cr - 128) * 0.7139 B = Y + (Cb - 128) * 1.7718
import cv2 import numpy as np import matplotlib.pyplot as plt # DCT hyoer-parameter T = 8 K = 8 channel = 3 # BGR -> Y Cb Cr def BGR2YCbCr(img): H, W, _ = img.shape ycbcr = np.zeros([H, W, 3], dtype=np.float32) ycbcr[..., 0] = 0.2990 * img[..., 2] + 0.5870 * img[..., 1] + 0.1140 * img[..., 0] ycbcr[..., 1] = -0.1687 * img[..., 2] - 0.3313 * img[..., 1] + 0.5 * img[..., 0] + 128. ycbcr[..., 2] = 0.5 * img[..., 2] - 0.4187 * img[..., 1] - 0.0813 * img[..., 0] + 128. return ycbcr # Y Cb Cr -> BGR def YCbCr2BGR(ycbcr): H, W, _ = ycbcr.shape out = np.zeros([H, W, channel], dtype=np.float32) out[..., 2] = ycbcr[..., 0] + (ycbcr[..., 2] - 128.) * 1.4020 out[..., 1] = ycbcr[..., 0] - (ycbcr[..., 1] - 128.) * 0.3441 - (ycbcr[..., 2] - 128.) * 0.7139 out[..., 0] = ycbcr[..., 0] + (ycbcr[..., 1] - 128.) * 1.7718 out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # DCT weight def DCT_w(x, y, u, v): cu = 1. cv = 1. if u == 0: cu /= np.sqrt(2) if v == 0: cv /= np.sqrt(2) theta = np.pi / (2 * T) return (( 2 * cu * cv / T) * np.cos((2*x+1)*u*theta) * np.cos((2*y+1)*v*theta)) # DCT def dct(img): H, W, _ = img.shape F = np.zeros((H, W, channel), dtype=np.float32) for c in range(channel): for yi in range(0, H, T): for xi in range(0, W, T): for v in range(T): for u in range(T): for y in range(T): for x in range(T): F[v+yi, u+xi, c] += img[y+yi, x+xi, c] * DCT_w(x,y,u,v) return F # IDCT def idct(F): H, W, _ = F.shape out = np.zeros((H, W, channel), dtype=np.float32) for c in range(channel): for yi in range(0, H, T): for xi in range(0, W, T): for y in range(T): for x in range(T): for v in range(K): for u in range(K): out[y+yi, x+xi, c] += F[v+yi, u+xi, c] * DCT_w(x,y,u,v) out = np.clip(out, 0, 255) out = np.round(out).astype(np.uint8) return out # Quantization def quantization(F): H, W, _ = F.shape Q = np.array(((16, 11, 10, 16, 24, 40, 51, 61), (12, 12, 14, 19, 26, 58, 60, 55), (14, 13, 16, 24, 40, 57, 69, 56), (14, 17, 22, 29, 51, 87, 80, 62), (18, 22, 37, 56, 68, 109, 103, 77), (24, 35, 55, 64, 81, 104, 113, 92), (49, 64, 78, 87, 103, 121, 120, 101), (72, 92, 95, 98, 112, 100, 103, 99)), dtype=np.float32) for ys in range(0, H, T): for xs in range(0, W, T): for c in range(channel): F[ys: ys + T, xs: xs + T, c] = np.round(F[ys: ys + T, xs: xs + T, c] / Q) * Q return F # JPEG without Hufman coding def JPEG(img): # BGR -> Y Cb Cr ycbcr = BGR2YCbCr(img) # DCT F = dct(ycbcr) # quantization F = quantization(F) # IDCT ycbcr = idct(F) # Y Cb Cr -> BGR out = YCbCr2BGR(ycbcr) return out # MSE def MSE(img1, img2): H, W, _ = img1.shape mse = np.sum((img1 - img2) ** 2) / (H * W * channel) return mse # PSNR def PSNR(mse, vmax=255): return 10 * np.log10(vmax * vmax / mse) # bitrate def BITRATE(): return 1. * T * K * K / T / T # Read image img = cv2.imread("imori.jpg").astype(np.float32) # JPEG out = JPEG(img) # MSE mse = MSE(img, out) # PSNR psnr = PSNR(mse) # bitrate bitrate = BITRATE() print("MSE:", mse) print("PSNR:", psnr) print("bitrate:", bitrate) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
239
MIT
gasyori_100_knocks
pythonを用いて、YCbCr表色系にし、DCT後、Yを量子化テーブルQ1、CbとCrをQ2で量子化し、IDCTで画像を復元せよ。また、画像の容量を比較せよ。 アルゴリズムは、 1. RGB を YCbCrに変換 2. YCbCrをDCT 3. DCTしたものを量子化 4. 量子化したものをIDCT 5. IDCTしたYCbCrをRGBに変換 これはJPEGで実際に使われるデータ量削減の手法であり、Q1,Q2はJPEGの仕様書に則って次式で定義される。 Q1 = np.array(((16, 11, 10, 16, 24, 40, 51, 61), (12, 12, 14, 19, 26, 58, 60, 55), (14, 13, 16, 24, 40, 57, 69, 56), (14, 17, 22, 29, 51, 87, 80, 62), (18, 22, 37, 56, 68, 109, 103, 77), (24, 35, 55, 64, 81, 104, 113, 92), (49, 64, 78, 87, 103, 121, 120, 101), (72, 92, 95, 98, 112, 100, 103, 99)), dtype=np.float32) Q2 = np.array(((17, 18, 24, 47, 99, 99, 99, 99), (18, 21, 26, 66, 99, 99, 99, 99), (24, 26, 56, 99, 99, 99, 99, 99), (47, 66, 99, 99, 99, 99, 99, 99), (99, 99, 99, 99, 99, 99, 99, 99), (99, 99, 99, 99, 99, 99, 99, 99), (99, 99, 99, 99, 99, 99, 99, 99), (99, 99, 99, 99, 99, 99, 99, 99)), dtype=np.float32)
import cv2 import numpy as np import matplotlib.pyplot as plt def Canny_step1(img): # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Gaussian filter for grayscale def gaussian_filter(img, K_size=3, sigma=1.3): if len(img.shape) == 3: H, W, C = img.shape gray = False else: img = np.expand_dims(img, axis=-1) H, W, C = img.shape gray = True ## Zero padding pad = K_size // 2 out = np.zeros([H + pad * 2, W + pad * 2, C], dtype=np.float) out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float) ## prepare Kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(-pad, -pad + K_size): for y in range(-pad, -pad + K_size): K[y + pad, x + pad] = np.exp( - (x ** 2 + y ** 2) / (2 * (sigma ** 2))) K /= (2 * np.pi * sigma * sigma) K /= K.sum() tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.sum(K * tmp[y : y + K_size, x : x + K_size, c]) out = np.clip(out, 0, 255) out = out[pad : pad + H, pad : pad + W] #out = out.astype(np.uint8) if gray: out = out[..., 0] return out # sobel filter def sobel_filter(img, K_size=3): if len(img.shape) == 3: H, W, C = img.shape else: #img = np.expand_dims(img, axis=-1) H, W = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() ## Sobel vertical Kv = [[1., 2., 1.],[0., 0., 0.], [-1., -2., -1.]] ## Sobel horizontal Kh = [[1., 0., -1.],[2., 0., -2.],[1., 0., -1.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y : y + K_size, x : x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y : y + K_size, x : x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad : pad + H, pad : pad + W].astype(np.uint8) out_h = out_h[pad : pad + H, pad : pad + W].astype(np.uint8) return out_v, out_h def get_edge_angle(fx, fy): # get edge strength edge = np.sqrt(np.power(fx, 2) + np.power(fy, 2)) fx = np.maximum(fx, 1e-5) # get edge angle angle = np.arctan(fy / fx) return edge, angle def angle_quantization(angle): angle = angle / np.pi * 180 angle[angle < -22.5] = 180 + angle[angle < -22.5] _angle = np.zeros_like(angle, dtype=np.uint8) _angle[np.where(angle <= 22.5)] = 0 _angle[np.where((angle > 22.5) & (angle <= 67.5))] = 45 _angle[np.where((angle > 67.5) & (angle <= 112.5))] = 90 _angle[np.where((angle > 112.5) & (angle <= 157.5))] = 135 return _angle # grayscale gray = BGR2GRAY(img) # gaussian filtering gaussian = gaussian_filter(gray, K_size=5, sigma=1.4) # sobel filtering fy, fx = sobel_filter(gaussian, K_size=3) # get edge strength, angle edge, angle = get_edge_angle(fx, fy) # angle quantization angle = angle_quantization(angle) return edge, angle # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Canny (step1) edge, angle = Canny_step1(img) edge = edge.astype(np.uint8) angle = angle.astype(np.uint8) # Save result cv2.imwrite("out.jpg", edge) cv2.imshow("result", edge) cv2.imwrite("out2.jpg", angle) cv2.imshow("result2", angle) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
240
MIT
gasyori_100_knocks
Canny法は、 1. ガウシアンフィルタを掛ける 2. x, y方向のSobelフィルタを掛け、それらからエッジ強度とエッジ勾配を求める 3. エッジ勾配の値から、Non-maximum suppression によりエッジの細線化を行う 4. ヒステリシスによる閾値処理を行う 以上により、画像からエッジ部分を抜き出す手法である。 pythonを用いて、1と2の処理を実装しなさい。 処理手順は、 1. 画像をグレースケール化する 2. ガウシアンフィルタ(5x5, s=1.4)をかける 3. x方向、y方向のsobelフィルタを掛け、画像の勾配画像fx, fyを求め、勾配強度と勾配角度を次式で求める。 勾配強度 edge = sqrt(fx^2 + fy^2) 勾配角度 angle = arctan(fy / fx) 4. 勾配角度を次式に沿って、量子化する。 ただし、angleはradianから角度(degree)にして、-22.5から157.5の範囲をとるように値が修正してから、以下の計算を行う。 angle = { 0 (if -22.5 < angle <= 22.5) 45 (if 22.5 < angle <= 67.5) 90 (if 67.5 < angle <= 112.5) 135 (if 112.5 < angle <= 157.5) ただし、フィルタリングをパディングする際は、numpy.pad()を用いて、エッジの値でパディングせよ。
import cv2 import numpy as np import matplotlib.pyplot as plt def Canny_step2(img): # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Gaussian filter for grayscale def gaussian_filter(img, K_size=3, sigma=1.3): if len(img.shape) == 3: H, W, C = img.shape else: img = np.expand_dims(img, axis=-1) H, W, C = img.shape ## Zero padding pad = K_size // 2 out = np.zeros([H + pad * 2, W + pad * 2, C], dtype=np.float) out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float) ## prepare Kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(-pad, -pad + K_size): for y in range(-pad, -pad + K_size): K[y + pad, x + pad] = np.exp( - (x ** 2 + y ** 2) / (2 * (sigma ** 2))) #K /= (sigma * np.sqrt(2 * np.pi)) K /= (2 * np.pi * sigma * sigma) K /= K.sum() tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.sum(K * tmp[y : y + K_size, x : x + K_size, c]) out = np.clip(out, 0, 255) out = out[pad : pad + H, pad : pad + W] out = out.astype(np.uint8) out = out[..., 0] return out # sobel filter def sobel_filter(img, K_size=3): if len(img.shape) == 3: H, W, C = img.shape else: H, W = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() ## Sobel vertical Kv = [[1., 2., 1.],[0., 0., 0.], [-1., -2., -1.]] ## Sobel horizontal Kh = [[1., 0., -1.],[2., 0., -2.],[1., 0., -1.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y: y + K_size, x: x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y: y + K_size, x: x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad: pad + H, pad: pad + W].astype(np.uint8) out_h = out_h[pad: pad + H, pad: pad + W].astype(np.uint8) return out_v, out_h def get_edge_angle(fx, fy): # get edge strength edge = np.sqrt(np.power(fx.astype(np.float32), 2) + np.power(fy.astype(np.float32), 2)) edge = np.clip(edge, 0, 255) fx = np.maximum(fx, 1e-5) #fx[np.abs(fx) <= 1e-5] = 1e-5 # get edge angle angle = np.arctan(fy / fx) return edge, angle def angle_quantization(angle): angle = angle / np.pi * 180 angle[angle < -22.5] = 180 + angle[angle < -22.5] _angle = np.zeros_like(angle, dtype=np.uint8) _angle[np.where(angle <= 22.5)] = 0 _angle[np.where((angle > 22.5) & (angle <= 67.5))] = 45 _angle[np.where((angle > 67.5) & (angle <= 112.5))] = 90 _angle[np.where((angle > 112.5) & (angle <= 157.5))] = 135 return _angle def non_maximum_suppression(angle, edge): H, W = angle.shape _edge = edge.copy() for y in range(H): for x in range(W): if angle[y, x] == 0: dx1, dy1, dx2, dy2 = -1, 0, 1, 0 elif angle[y, x] == 45: dx1, dy1, dx2, dy2 = -1, 1, 1, -1 elif angle[y, x] == 90: dx1, dy1, dx2, dy2 = 0, -1, 0, 1 elif angle[y, x] == 135: dx1, dy1, dx2, dy2 = -1, -1, 1, 1 if x == 0: dx1 = max(dx1, 0) dx2 = max(dx2, 0) if x == W-1: dx1 = min(dx1, 0) dx2 = min(dx2, 0) if y == 0: dy1 = max(dy1, 0) dy2 = max(dy2, 0) if y == H-1: dy1 = min(dy1, 0) dy2 = min(dy2, 0) if max(max(edge[y, x], edge[y + dy1, x + dx1]), edge[y + dy2, x + dx2]) != edge[y, x]: _edge[y, x] = 0 return _edge # grayscale gray = BGR2GRAY(img) # gaussian filtering gaussian = gaussian_filter(gray, K_size=5, sigma=1.4) # sobel filtering fy, fx = sobel_filter(gaussian, K_size=3) # get edge strength, angle edge, angle = get_edge_angle(fx, fy) # angle quantization angle = angle_quantization(angle) # non maximum suppression edge = non_maximum_suppression(angle, edge) return edge, angle # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Canny (step2) edge, angle = Canny_step2(img) edge = edge.astype(np.uint8) angle = angle.astype(np.uint8) # Save result cv2.imwrite("out.jpg", edge) cv2.imshow("result", edge) cv2.imwrite("out2.jpg", angle) cv2.imshow("result2", angle) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
241
MIT
gasyori_100_knocks
Canny法は、 1. ガウシアンフィルタを掛ける 2. x, y方向のSobelフィルタを掛け、それらからエッジ強度とエッジ勾配を求める 3. エッジ勾配の値から、Non-maximum suppression によりエッジの細線化を行う 4. ヒステリシスによる閾値処理を行う 以上により、画像からエッジ部分を抜き出す手法である。 pythonを用いて3の処理を実装しないさい。 処理1、2で求めた勾配角度から、Non-maximum suppressionを行い、エッジ線を細くする(細線化)。 Non-maximum suppression(NMS)とは非最大値以外を除去する作業の総称である。(他のタスクでもこの名前はよく出る) ここでは、注目している箇所の勾配角度の法線方向の隣接ピクセルの3つの勾配強度を比較して、最大値ならそのまま値をいじらずに、最大値でなければ強度を0にする、 つまり、勾配強度edge(x,y)に注目している際に、勾配角度angle(x,y)によって次式のようにedge(x,y)を変更する。 if angle(x,y) = 0 if edge(x,y), edge(x-1,y), edge(x+1,y)で edge(x,y)が最大じゃない then edge(x,y) = 0 if angle(x,y) = 45 if edge(x,y), edge(x-1,y+1), edge(x+1,y-1)で edge(x,y)が最大じゃない then edge(x,y) = 0 if angle(x,y) = 90 if edge(x,y), edge(x,y-1), edge(x,y+1)で edge(x,y)が最大じゃない then edge(x,y) = 0 if angle(x,y) = 135 if edge(x,y), edge(x-1,y-1), edge(x+1,y+1)で edge(x,y)が最大じゃない then edge(x,y) = 0
import cv2 import numpy as np import matplotlib.pyplot as plt def Canny(img): # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Gaussian filter for grayscale def gaussian_filter(img, K_size=3, sigma=1.3): if len(img.shape) == 3: H, W, C = img.shape gray = False else: img = np.expand_dims(img, axis=-1) H, W, C = img.shape gray = True ## Zero padding pad = K_size // 2 out = np.zeros([H + pad * 2, W + pad * 2, C], dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) ## prepare Kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(-pad, -pad + K_size): for y in range(-pad, -pad + K_size): K[y + pad, x + pad] = np.exp( - (x ** 2 + y ** 2) / (2 * sigma * sigma)) #K /= (sigma * np.sqrt(2 * np.pi)) K /= (2 * np.pi * sigma * sigma) K /= K.sum() tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.sum(K * tmp[y : y + K_size, x : x + K_size, c]) out = np.clip(out, 0, 255) out = out[pad : pad + H, pad : pad + W] out = out.astype(np.uint8) if gray: out = out[..., 0] return out # sobel filter def sobel_filter(img, K_size=3): if len(img.shape) == 3: H, W, C = img.shape else: H, W = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() ## Sobel vertical Kv = [[1., 2., 1.],[0., 0., 0.], [-1., -2., -1.]] ## Sobel horizontal Kh = [[1., 0., -1.],[2., 0., -2.],[1., 0., -1.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y : y + K_size, x : x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y : y + K_size, x : x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad : pad + H, pad : pad + W] out_v = out_v.astype(np.uint8) out_h = out_h[pad : pad + H, pad : pad + W] out_h = out_h.astype(np.uint8) return out_v, out_h def get_edge_angle(fx, fy): # get edge strength edge = np.sqrt(np.power(fx.astype(np.float32), 2) + np.power(fy.astype(np.float32), 2)) edge = np.clip(edge, 0, 255) fx = np.maximum(fx, 1e-10) #fx[np.abs(fx) <= 1e-5] = 1e-5 # get edge angle angle = np.arctan(fy / fx) return edge, angle def angle_quantization(angle): angle = angle / np.pi * 180 angle[angle < -22.5] = 180 + angle[angle < -22.5] _angle = np.zeros_like(angle, dtype=np.uint8) _angle[np.where(angle <= 22.5)] = 0 _angle[np.where((angle > 22.5) & (angle <= 67.5))] = 45 _angle[np.where((angle > 67.5) & (angle <= 112.5))] = 90 _angle[np.where((angle > 112.5) & (angle <= 157.5))] = 135 return _angle def non_maximum_suppression(angle, edge): H, W = angle.shape _edge = edge.copy() for y in range(H): for x in range(W): if angle[y, x] == 0: dx1, dy1, dx2, dy2 = -1, 0, 1, 0 elif angle[y, x] == 45: dx1, dy1, dx2, dy2 = -1, 1, 1, -1 elif angle[y, x] == 90: dx1, dy1, dx2, dy2 = 0, -1, 0, 1 elif angle[y, x] == 135: dx1, dy1, dx2, dy2 = -1, -1, 1, 1 if x == 0: dx1 = max(dx1, 0) dx2 = max(dx2, 0) if x == W-1: dx1 = min(dx1, 0) dx2 = min(dx2, 0) if y == 0: dy1 = max(dy1, 0) dy2 = max(dy2, 0) if y == H-1: dy1 = min(dy1, 0) dy2 = min(dy2, 0) if max(max(edge[y, x], edge[y + dy1, x + dx1]), edge[y + dy2, x + dx2]) != edge[y, x]: _edge[y, x] = 0 return _edge def hysterisis(edge, HT=100, LT=30): H, W = edge.shape # Histeresis threshold edge[edge >= HT] = 255 edge[edge <= LT] = 0 _edge = np.zeros((H + 2, W + 2), dtype=np.float32) _edge[1 : H + 1, 1 : W + 1] = edge ## 8 - Nearest neighbor nn = np.array(((1., 1., 1.), (1., 0., 1.), (1., 1., 1.)), dtype=np.float32) for y in range(1, H+2): for x in range(1, W+2): if _edge[y, x] < LT or _edge[y, x] > HT: continue if np.max(_edge[y-1:y+2, x-1:x+2] * nn) >= HT: _edge[y, x] = 255 else: _edge[y, x] = 0 edge = _edge[1:H+1, 1:W+1] return edge # grayscale gray = BGR2GRAY(img) # gaussian filtering gaussian = gaussian_filter(gray, K_size=5, sigma=1.4) # sobel filtering fy, fx = sobel_filter(gaussian, K_size=3) # get edge strength, angle edge, angle = get_edge_angle(fx, fy) # angle quantization angle = angle_quantization(angle) # non maximum suppression edge = non_maximum_suppression(angle, edge) # hysterisis threshold out = hysterisis(edge, 50, 20) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Canny edge = Canny(img) out = edge.astype(np.uint8) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
242
MIT
gasyori_100_knocks
Canny法は、 1. ガウシアンフィルタを掛ける 2. x, y方向のSobelフィルタを掛け、それらからエッジ強度とエッジ勾配を求める 3. エッジ勾配の値から、Non-maximum suppression によりエッジの細線化を行う 4. ヒステリシスによる閾値処理を行う 以上により、画像からエッジ部分を抜き出す手法である。 pythonを用いて、4の処理を実装する。 ここでは、閾値により勾配強度の二値化を行うがCanny法では二つの閾値(HT: high thoresholdとLT: low threshold)を用いる。 はじめに、 1. 勾配強度edge(x,y)がHT以上の場合はedge(x,y)=255 2. LT以下のedge(x,y)=0 3. LT < edge(x,y) < HTの時、周り8ピクセルの勾配強度でHTより大きい値が存在すれば、edge(x,y)=255 ここでは、HT=50, LT=20とする。ちなみに閾値の値は結果を見ながら判断するしかない。 以上のアルゴリズムによって、Canny法が行われる。
import cv2 import numpy as np import matplotlib.pyplot as plt def Canny(img): # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Gaussian filter for grayscale def gaussian_filter(img, K_size=3, sigma=1.3): if len(img.shape) == 3: H, W, C = img.shape gray = False else: img = np.expand_dims(img, axis=-1) H, W, C = img.shape gray = True ## Zero padding pad = K_size // 2 out = np.zeros([H + pad * 2, W + pad * 2, C], dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) ## prepare Kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(-pad, -pad + K_size): for y in range(-pad, -pad + K_size): K[y + pad, x + pad] = np.exp( - (x ** 2 + y ** 2) / (2 * sigma * sigma)) #K /= (sigma * np.sqrt(2 * np.pi)) K /= (2 * np.pi * sigma * sigma) K /= K.sum() tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.sum(K * tmp[y : y + K_size, x : x + K_size, c]) out = np.clip(out, 0, 255) out = out[pad : pad + H, pad : pad + W] out = out.astype(np.uint8) if gray: out = out[..., 0] return out # sobel filter def sobel_filter(img, K_size=3): if len(img.shape) == 3: H, W, C = img.shape else: H, W = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() ## Sobel vertical Kv = [[1., 2., 1.],[0., 0., 0.], [-1., -2., -1.]] ## Sobel horizontal Kh = [[1., 0., -1.],[2., 0., -2.],[1., 0., -1.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y : y + K_size, x : x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y : y + K_size, x : x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad : pad + H, pad : pad + W] out_v = out_v.astype(np.uint8) out_h = out_h[pad : pad + H, pad : pad + W] out_h = out_h.astype(np.uint8) return out_v, out_h def get_edge_angle(fx, fy): # get edge strength edge = np.sqrt(np.power(fx.astype(np.float32), 2) + np.power(fy.astype(np.float32), 2)) edge = np.clip(edge, 0, 255) fx = np.maximum(fx, 1e-10) #fx[np.abs(fx) <= 1e-5] = 1e-5 # get edge angle angle = np.arctan(fy / fx) return edge, angle def angle_quantization(angle): angle = angle / np.pi * 180 angle[angle < -22.5] = 180 + angle[angle < -22.5] _angle = np.zeros_like(angle, dtype=np.uint8) _angle[np.where(angle <= 22.5)] = 0 _angle[np.where((angle > 22.5) & (angle <= 67.5))] = 45 _angle[np.where((angle > 67.5) & (angle <= 112.5))] = 90 _angle[np.where((angle > 112.5) & (angle <= 157.5))] = 135 return _angle def non_maximum_suppression(angle, edge): H, W = angle.shape _edge = edge.copy() for y in range(H): for x in range(W): if angle[y, x] == 0: dx1, dy1, dx2, dy2 = -1, 0, 1, 0 elif angle[y, x] == 45: dx1, dy1, dx2, dy2 = -1, 1, 1, -1 elif angle[y, x] == 90: dx1, dy1, dx2, dy2 = 0, -1, 0, 1 elif angle[y, x] == 135: dx1, dy1, dx2, dy2 = -1, -1, 1, 1 if x == 0: dx1 = max(dx1, 0) dx2 = max(dx2, 0) if x == W-1: dx1 = min(dx1, 0) dx2 = min(dx2, 0) if y == 0: dy1 = max(dy1, 0) dy2 = max(dy2, 0) if y == H-1: dy1 = min(dy1, 0) dy2 = min(dy2, 0) if max(max(edge[y, x], edge[y + dy1, x + dx1]), edge[y + dy2, x + dx2]) != edge[y, x]: _edge[y, x] = 0 return _edge def hysterisis(edge, HT=100, LT=30): H, W = edge.shape # Histeresis threshold edge[edge >= HT] = 255 edge[edge <= LT] = 0 _edge = np.zeros((H + 2, W + 2), dtype=np.float32) _edge[1 : H + 1, 1 : W + 1] = edge ## 8 - Nearest neighbor nn = np.array(((1., 1., 1.), (1., 0., 1.), (1., 1., 1.)), dtype=np.float32) for y in range(1, H+2): for x in range(1, W+2): if _edge[y, x] < LT or _edge[y, x] > HT: continue if np.max(_edge[y-1:y+2, x-1:x+2] * nn) >= HT: _edge[y, x] = 255 else: _edge[y, x] = 0 edge = _edge[1:H+1, 1:W+1] return edge # grayscale gray = BGR2GRAY(img) # gaussian filtering gaussian = gaussian_filter(gray, K_size=5, sigma=1.4) # sobel filtering fy, fx = sobel_filter(gaussian, K_size=3) # get edge strength, angle edge, angle = get_edge_angle(fx, fy) # angle quantization angle = angle_quantization(angle) # non maximum suppression edge = non_maximum_suppression(angle, edge) # hysterisis threshold out = hysterisis(edge, 100, 30) return out def Hough_Line_step1(edge): ## Voting def voting(edge): H, W = edge.shape drho = 1 dtheta = 1 # get rho max length rho_max = np.ceil(np.sqrt(H ** 2 + W ** 2)).astype(np.int) # hough table hough = np.zeros((rho_max * 2, 180), dtype=np.int) # get index of edge ind = np.where(edge == 255) ## hough transformation for y, x in zip(ind[0], ind[1]): for theta in range(0, 180, dtheta): # get polar coordinat4s t = np.pi / 180 * theta rho = int(x * np.cos(t) + y * np.sin(t)) # vote hough[rho + rho_max, theta] += 1 out = hough.astype(np.uint8) return out # voting out = voting(edge) return out # Read image img = cv2.imread("thorino.jpg").astype(np.float32) # Canny edge = Canny(img) # Hough out = Hough_Line_step1(edge) out = out.astype(np.uint8) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
243
MIT
gasyori_100_knocks
Hough変換とは、座標を直交座標から極座標に変換することにより数式に沿って直線や円など一定の形状を検出する手法である。 ある直線状の点では極座標に変換すると一定のr, tにおいて交わる。 その点が検出すべき直線を表すパラメータであり、このパラメータを逆変換すると直線の方程式を求めることができる。 方法としては、 1. エッジ画像(ここではCannyの出力)からエッジのピクセルにおいてHough変換を行う。 2. Hough変換後の値のヒストグラムをとり、極大点を選ぶ。 3. 極大点のr, tの値をHough逆変換して検出した直線のパラメータを得る。 となる。 pythonを用いて1のHough変換を行いヒストグラムを作成しなさい。 アルゴリズムは、 1. 画像の対角線の長さrmaxを求める。 2. エッジ箇所(x,y)において、t = 0-179で一度ずつtを変えながら、次式によりHough変換を行う。 rho = x * cos(t) + y * sin(t) 3. 「ボーティング(投票)」 [2 x rmax, 180]のサイズの表を用意し、1で得たtable(rho, t) に1を足す。2で求めたrhoは[-rmax, rmax]の範囲を取るので、ボーティングの時には注意! ボーティングでは、一定の箇所に集中する。 今回はtorino.jpgを用いて、ボーディングした表を図示せよ。 Cannyのパラメータは, gaussian filter(5x5, s=1.4), HT = 100, LT = 30で使用せよ。
import cv2 import numpy as np import matplotlib.pyplot as plt def Canny(img): # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Gaussian filter for grayscale def gaussian_filter(img, K_size=3, sigma=1.3): if len(img.shape) == 3: H, W, C = img.shape gray = False else: img = np.expand_dims(img, axis=-1) H, W, C = img.shape gray = True ## Zero padding pad = K_size // 2 out = np.zeros([H + pad * 2, W + pad * 2, C], dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) ## prepare Kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(-pad, -pad + K_size): for y in range(-pad, -pad + K_size): K[y + pad, x + pad] = np.exp( - (x ** 2 + y ** 2) / (2 * sigma * sigma)) #K /= (sigma * np.sqrt(2 * np.pi)) K /= (2 * np.pi * sigma * sigma) K /= K.sum() tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.sum(K * tmp[y : y + K_size, x : x + K_size, c]) out = np.clip(out, 0, 255) out = out[pad : pad + H, pad : pad + W] out = out.astype(np.uint8) if gray: out = out[..., 0] return out # sobel filter def sobel_filter(img, K_size=3): if len(img.shape) == 3: H, W, C = img.shape else: H, W = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() ## Sobel vertical Kv = [[1., 2., 1.],[0., 0., 0.], [-1., -2., -1.]] ## Sobel horizontal Kh = [[1., 0., -1.],[2., 0., -2.],[1., 0., -1.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y : y + K_size, x : x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y : y + K_size, x : x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad : pad + H, pad : pad + W] out_v = out_v.astype(np.uint8) out_h = out_h[pad : pad + H, pad : pad + W] out_h = out_h.astype(np.uint8) return out_v, out_h def get_edge_angle(fx, fy): # get edge strength edge = np.sqrt(np.power(fx.astype(np.float32), 2) + np.power(fy.astype(np.float32), 2)) edge = np.clip(edge, 0, 255) fx = np.maximum(fx, 1e-10) #fx[np.abs(fx) <= 1e-5] = 1e-5 # get edge angle angle = np.arctan(fy / fx) return edge, angle def angle_quantization(angle): angle = angle / np.pi * 180 angle[angle < -22.5] = 180 + angle[angle < -22.5] _angle = np.zeros_like(angle, dtype=np.uint8) _angle[np.where(angle <= 22.5)] = 0 _angle[np.where((angle > 22.5) & (angle <= 67.5))] = 45 _angle[np.where((angle > 67.5) & (angle <= 112.5))] = 90 _angle[np.where((angle > 112.5) & (angle <= 157.5))] = 135 return _angle def non_maximum_suppression(angle, edge): H, W = angle.shape _edge = edge.copy() for y in range(H): for x in range(W): if angle[y, x] == 0: dx1, dy1, dx2, dy2 = -1, 0, 1, 0 elif angle[y, x] == 45: dx1, dy1, dx2, dy2 = -1, 1, 1, -1 elif angle[y, x] == 90: dx1, dy1, dx2, dy2 = 0, -1, 0, 1 elif angle[y, x] == 135: dx1, dy1, dx2, dy2 = -1, -1, 1, 1 if x == 0: dx1 = max(dx1, 0) dx2 = max(dx2, 0) if x == W-1: dx1 = min(dx1, 0) dx2 = min(dx2, 0) if y == 0: dy1 = max(dy1, 0) dy2 = max(dy2, 0) if y == H-1: dy1 = min(dy1, 0) dy2 = min(dy2, 0) if max(max(edge[y, x], edge[y + dy1, x + dx1]), edge[y + dy2, x + dx2]) != edge[y, x]: _edge[y, x] = 0 return _edge def hysterisis(edge, HT=100, LT=30): H, W = edge.shape # Histeresis threshold edge[edge >= HT] = 255 edge[edge <= LT] = 0 _edge = np.zeros((H + 2, W + 2), dtype=np.float32) _edge[1 : H + 1, 1 : W + 1] = edge ## 8 - Nearest neighbor nn = np.array(((1., 1., 1.), (1., 0., 1.), (1., 1., 1.)), dtype=np.float32) for y in range(1, H+2): for x in range(1, W+2): if _edge[y, x] < LT or _edge[y, x] > HT: continue if np.max(_edge[y-1:y+2, x-1:x+2] * nn) >= HT: _edge[y, x] = 255 else: _edge[y, x] = 0 edge = _edge[1:H+1, 1:W+1] return edge # grayscale gray = BGR2GRAY(img) # gaussian filtering gaussian = gaussian_filter(gray, K_size=5, sigma=1.4) # sobel filtering fy, fx = sobel_filter(gaussian, K_size=3) # get edge strength, angle edge, angle = get_edge_angle(fx, fy) # angle quantization angle = angle_quantization(angle) # non maximum suppression edge = non_maximum_suppression(angle, edge) # hysterisis threshold out = hysterisis(edge, 100, 30) return out def Hough_Line_step2(edge): ## Voting def voting(edge): H, W = edge.shape drho = 1 dtheta = 1 # get rho max length rho_max = np.ceil(np.sqrt(H ** 2 + W ** 2)).astype(np.int) # hough table hough = np.zeros((rho_max * 2, 180), dtype=np.int) # get index of edge ind = np.where(edge == 255) ## hough transformation for y, x in zip(ind[0], ind[1]): for theta in range(0, 180, dtheta): # get polar coordinat4s t = np.pi / 180 * theta rho = int(x * np.cos(t) + y * np.sin(t)) # vote hough[rho + rho_max, theta] += 1 out = hough.astype(np.uint8) return out # non maximum suppression def non_maximum_suppression(hough): rho_max, _ = hough.shape ## non maximum suppression for y in range(rho_max): for x in range(180): # get 8 nearest neighbor x1 = max(x-1, 0) x2 = min(x+2, 180) y1 = max(y-1, 0) y2 = min(y+2, rho_max-1) if np.max(hough[y1:y2, x1:x2]) == hough[y,x] and hough[y, x] != 0: pass #hough[y,x] = 255 else: hough[y,x] = 0 # for hough visualization # get top-10 x index of hough table ind_x = np.argsort(hough.ravel())[::-1][:20] # get y index ind_y = ind_x.copy() thetas = ind_x % 180 rhos = ind_y // 180 _hough = np.zeros_like(hough, dtype=np.int) _hough[rhos, thetas] = 255 return _hough # voting hough = voting(edge) # non maximum suppression out = non_maximum_suppression(hough) return out # Read image img = cv2.imread("thorino.jpg").astype(np.float32) # Canny edge = Canny(img) # Hough out = Hough_Line_step2(edge) out = out.astype(np.uint8) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
244
MIT
gasyori_100_knocks
Hough変換とは、座標を直交座標から極座標に変換することにより数式に沿って直線や円など一定の形状を検出する手法である。 ある直線状の点では極座標に変換すると一定のr, tにおいて交わる。 その点が検出すべき直線を表すパラメータであり、このパラメータを逆変換すると直線の方程式を求めることができる。 方法としては、 1. エッジ画像(ここではCannyの出力)からエッジのピクセルにおいてHough変換を行う。 2. Hough変換後の値のヒストグラムをとり、極大点を選ぶ。 3. 極大点のr, tの値をHough逆変換して検出した直線のパラメータを得る。 となる。 pythonを用いて、2の処理を実装しなさい。 1の処理で得られた表では、ある一定の箇所付近に多く投票される。 ここでは、その付近の極大値を抜き出す操作を行え。 今回はボーディングが多い箇所を上位20個抜き出し、図示せよ。(C++の解答は上位30個にしてます。なんか20だと同じような結果にらなかったので、、) NMSのアルゴリズムは、 1. 表において、周囲8マス(8近傍)より注目ピクセルの得票数が多ければそのまま。 2. 注目ピクセルの値が少なければ0にする。
import cv2 import numpy as np import matplotlib.pyplot as plt def Canny(img): # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Gaussian filter for grayscale def gaussian_filter(img, K_size=3, sigma=1.3): if len(img.shape) == 3: H, W, C = img.shape gray = False else: img = np.expand_dims(img, axis=-1) H, W, C = img.shape gray = True ## Zero padding pad = K_size // 2 out = np.zeros([H + pad * 2, W + pad * 2, C], dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) ## prepare Kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(-pad, -pad + K_size): for y in range(-pad, -pad + K_size): K[y + pad, x + pad] = np.exp( - (x ** 2 + y ** 2) / (2 * sigma * sigma)) #K /= (sigma * np.sqrt(2 * np.pi)) K /= (2 * np.pi * sigma * sigma) K /= K.sum() tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.sum(K * tmp[y : y + K_size, x : x + K_size, c]) out = np.clip(out, 0, 255) out = out[pad : pad + H, pad : pad + W] out = out.astype(np.uint8) if gray: out = out[..., 0] return out # sobel filter def sobel_filter(img, K_size=3): if len(img.shape) == 3: H, W, C = img.shape else: H, W = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() ## Sobel vertical Kv = [[1., 2., 1.],[0., 0., 0.], [-1., -2., -1.]] ## Sobel horizontal Kh = [[1., 0., -1.],[2., 0., -2.],[1., 0., -1.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y : y + K_size, x : x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y : y + K_size, x : x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad : pad + H, pad : pad + W] out_v = out_v.astype(np.uint8) out_h = out_h[pad : pad + H, pad : pad + W] out_h = out_h.astype(np.uint8) return out_v, out_h def get_edge_angle(fx, fy): # get edge strength edge = np.sqrt(np.power(fx.astype(np.float32), 2) + np.power(fy.astype(np.float32), 2)) edge = np.clip(edge, 0, 255) fx = np.maximum(fx, 1e-10) #fx[np.abs(fx) <= 1e-5] = 1e-5 # get edge angle angle = np.arctan(fy / fx) return edge, angle def angle_quantization(angle): angle = angle / np.pi * 180 angle[angle < -22.5] = 180 + angle[angle < -22.5] _angle = np.zeros_like(angle, dtype=np.uint8) _angle[np.where(angle <= 22.5)] = 0 _angle[np.where((angle > 22.5) & (angle <= 67.5))] = 45 _angle[np.where((angle > 67.5) & (angle <= 112.5))] = 90 _angle[np.where((angle > 112.5) & (angle <= 157.5))] = 135 return _angle def non_maximum_suppression(angle, edge): H, W = angle.shape _edge = edge.copy() for y in range(H): for x in range(W): if angle[y, x] == 0: dx1, dy1, dx2, dy2 = -1, 0, 1, 0 elif angle[y, x] == 45: dx1, dy1, dx2, dy2 = -1, 1, 1, -1 elif angle[y, x] == 90: dx1, dy1, dx2, dy2 = 0, -1, 0, 1 elif angle[y, x] == 135: dx1, dy1, dx2, dy2 = -1, -1, 1, 1 if x == 0: dx1 = max(dx1, 0) dx2 = max(dx2, 0) if x == W-1: dx1 = min(dx1, 0) dx2 = min(dx2, 0) if y == 0: dy1 = max(dy1, 0) dy2 = max(dy2, 0) if y == H-1: dy1 = min(dy1, 0) dy2 = min(dy2, 0) if max(max(edge[y, x], edge[y + dy1, x + dx1]), edge[y + dy2, x + dx2]) != edge[y, x]: _edge[y, x] = 0 return _edge def hysterisis(edge, HT=100, LT=30): H, W = edge.shape # Histeresis threshold edge[edge >= HT] = 255 edge[edge <= LT] = 0 _edge = np.zeros((H + 2, W + 2), dtype=np.float32) _edge[1 : H + 1, 1 : W + 1] = edge ## 8 - Nearest neighbor nn = np.array(((1., 1., 1.), (1., 0., 1.), (1., 1., 1.)), dtype=np.float32) for y in range(1, H+2): for x in range(1, W+2): if _edge[y, x] < LT or _edge[y, x] > HT: continue if np.max(_edge[y-1:y+2, x-1:x+2] * nn) >= HT: _edge[y, x] = 255 else: _edge[y, x] = 0 edge = _edge[1:H+1, 1:W+1] return edge # grayscale gray = BGR2GRAY(img) # gaussian filtering gaussian = gaussian_filter(gray, K_size=5, sigma=1.4) # sobel filtering fy, fx = sobel_filter(gaussian, K_size=3) # get edge strength, angle edge, angle = get_edge_angle(fx, fy) # angle quantization angle = angle_quantization(angle) # non maximum suppression edge = non_maximum_suppression(angle, edge) # hysterisis threshold out = hysterisis(edge, 100, 30) return out def Hough_Line(edge, img): ## Voting def voting(edge): H, W = edge.shape drho = 1 dtheta = 1 # get rho max length rho_max = np.ceil(np.sqrt(H ** 2 + W ** 2)).astype(np.int) # hough table hough = np.zeros((rho_max * 2, 180), dtype=np.int) # get index of edge ind = np.where(edge == 255) ## hough transformation for y, x in zip(ind[0], ind[1]): for theta in range(0, 180, dtheta): # get polar coordinat4s t = np.pi / 180 * theta rho = int(x * np.cos(t) + y * np.sin(t)) # vote hough[rho + rho_max, theta] += 1 out = hough.astype(np.uint8) return out # non maximum suppression def non_maximum_suppression(hough): rho_max, _ = hough.shape ## non maximum suppression for y in range(rho_max): for x in range(180): # get 8 nearest neighbor x1 = max(x-1, 0) x2 = min(x+2, 180) y1 = max(y-1, 0) y2 = min(y+2, rho_max-1) if np.max(hough[y1:y2, x1:x2]) == hough[y,x] and hough[y, x] != 0: pass #hough[y,x] = 255 else: hough[y,x] = 0 return hough def inverse_hough(hough, img): H, W, _ = img.shape rho_max, _ = hough.shape out = img.copy() # get x, y index of hough table ind_x = np.argsort(hough.ravel())[::-1][:20] ind_y = ind_x.copy() thetas = ind_x % 180 rhos = ind_y // 180 - rho_max / 2 # each theta and rho for theta, rho in zip(thetas, rhos): # theta[radian] -> angle[degree] t = np.pi / 180. * theta # hough -> (x,y) for x in range(W): if np.sin(t) != 0: y = - (np.cos(t) / np.sin(t)) * x + (rho) / np.sin(t) y = int(y) if y >= H or y < 0: continue out[y, x] = [0, 0, 255] for y in range(H): if np.cos(t) != 0: x = - (np.sin(t) / np.cos(t)) * y + (rho) / np.cos(t) x = int(x) if x >= W or x < 0: continue out[y, x] = [0, 0, 255] out = out.astype(np.uint8) return out # voting hough = voting(edge) # non maximum suppression hough = non_maximum_suppression(hough) # inverse hough out = inverse_hough(hough, img) return out # Read image img = cv2.imread("thorino.jpg").astype(np.float32) # Canny edge = Canny(img) # Hough out = Hough_Line(edge, img) out = out.astype(np.uint8) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
245
MIT
gasyori_100_knocks
Hough変換とは、座標を直交座標から極座標に変換することにより数式に沿って直線や円など一定の形状を検出する手法である。 ある直線状の点では極座標に変換すると一定のr, tにおいて交わる。 その点が検出すべき直線を表すパラメータであり、このパラメータを逆変換すると直線の方程式を求めることができる。 方法としては、 1. エッジ画像(ここではCannyの出力)からエッジのピクセルにおいてHough変換を行う。 2. Hough変換後の値のヒストグラムをとり、極大点を選ぶ。 3. 極大点のr, tの値をHough逆変換して検出した直線のパラメータを得る。 となる。 pythonを用いて、2の処理で得られた極大値をHough逆変換をして直線を描画しなさい。これで、Hough変換による直線検出が完了する。 アルゴリズムは、 1. 極大点(r, t)を次式で逆変換する。 y = - cos(t) / sin(t) * x + r / sin(t) x = - sin(t) / cos(t) * y + r / cos(t) 2. 1の逆変換を極大点ごとにy = 0 - H-1, x = 0 - W-1 で行い、入力画像に検出した直線を描画せよ。 ただし、描画するのは赤線(R,G,B) = (255, 0, 0)とする。
mport cv2 import numpy as np import matplotlib.pyplot as plt # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Otsu Binalization def otsu_binarization(img, th=128): H, W = img.shape out = img.copy() max_sigma = 0 max_t = 0 # determine threshold for _t in range(1, 255): v0 = out[np.where(out < _t)] m0 = np.mean(v0) if len(v0) > 0 else 0. w0 = len(v0) / (H * W) v1 = out[np.where(out >= _t)] m1 = np.mean(v1) if len(v1) > 0 else 0. w1 = len(v1) / (H * W) sigma = w0 * w1 * ((m0 - m1) ** 2) if sigma > max_sigma: max_sigma = sigma max_t = _t # Binarization print("threshold >>", max_t) th = max_t out[out < th] = 0 out[out >= th] = 255 return out # Morphology Erode def Morphology_Erode(img, Dil_time=1): H, W = img.shape # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each dilate time out = img.copy() for i in range(Dil_time): tmp = np.pad(out, (1, 1), 'edge') for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) >= 255: out[y-1, x-1] = 255 return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Grayscale gray = BGR2GRAY(img) # Otsu's binarization otsu = otsu_binarization(gray) # Morphology - dilate out = Morphology_Erode(otsu, Dil_time=2) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
246
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgを大津の二値化したものに、モルフォロジー処理による膨張を2回行え。 モルフォロジー処理とは二値化画像の白(255)マス部分を4近傍(上下左右1マス)に膨張、または1マスだけ収縮させる処理をいう。 この膨張と収縮を何度も繰り返すことで1マスだけに存在する白マスを消したり(Q.49. オープニング処理)、本来つながってほしい白マスを結合させたりできる(Q.50. クロージング処理)。 モルフォロジー処理の膨張(Dilation)アルゴリズムは、 注目画素I(x, y)=0で、I(x, y-1), I(x-1, y), I(x+1, y), I(x, y+1)のどれか一つが255なら、I(x, y) = 255 とする。 つまり、上の処理を2回行えば2マス分膨張できることになる。 モルフォロジー処理の実装は例えば、[[0,1,0], [1,0,1], [0,1,0]] のフィルタを掛けた和が255以上なら膨張である、と考えることもできる。
import cv2 import numpy as np import matplotlib.pyplot as plt # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Otsu Binalization def otsu_binarization(img, th=128): H, W = img.shape out = img.copy() max_sigma = 0 max_t = 0 # determine threshold for _t in range(1, 255): v0 = out[np.where(out < _t)] m0 = np.mean(v0) if len(v0) > 0 else 0. w0 = len(v0) / (H * W) v1 = out[np.where(out >= _t)] m1 = np.mean(v1) if len(v1) > 0 else 0. w1 = len(v1) / (H * W) sigma = w0 * w1 * ((m0 - m1) ** 2) if sigma > max_sigma: max_sigma = sigma max_t = _t # Binarization print("threshold >>", max_t) th = max_t out[out < th] = 0 out[out >= th] = 255 return out # Morphology Dilate def Morphology_Dilate(img, Erode_time=1): H, W = img.shape out = img.copy() # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each erode for i in range(Erode_time): tmp = np.pad(out, (1, 1), 'edge') # erode for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) < 255*4: out[y-1, x-1] = 0 return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Grayscale gray = BGR2GRAY(img) # Otsu's binarization otsu = otsu_binarization(gray) # Morphology - dilate out = Morphology_Dilate(otsu, Erode_time=2) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
247
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgを大津の二値化したものに、モルフォロジー処理による収縮を2回行え。 モルフォロジー処理の収縮(Erosion)アルゴリズムは、 注目画素I(x, y)=255で、I(x, y-1), I(x-1, y), I(x+1, y), I(x, y+1)のどれか一つでも0なら、I(x, y) = 0 とする。 収縮処理は例えば、[[0,1,0], [1,0,1], [0,1,0]] のフィルタを掛けた和が255*4未満なら収縮である、と考えることもできる。
import cv2 import numpy as np import matplotlib.pyplot as plt # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Otsu Binalization def otsu_binarization(img, th=128): H, W = img.shape out = img.copy() max_sigma = 0 max_t = 0 # determine threshold for _t in range(1, 255): v0 = out[np.where(out < _t)] m0 = np.mean(v0) if len(v0) > 0 else 0. w0 = len(v0) / (H * W) v1 = out[np.where(out >= _t)] m1 = np.mean(v1) if len(v1) > 0 else 0. w1 = len(v1) / (H * W) sigma = w0 * w1 * ((m0 - m1) ** 2) if sigma > max_sigma: max_sigma = sigma max_t = _t # Binarization print("threshold >>", max_t) th = max_t out[out < th] = 0 out[out >= th] = 255 return out # Morphology Dilate def Morphology_Dilate(img, Erode_time=1): H, W = img.shape out = img.copy() # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each erode for i in range(Erode_time): tmp = np.pad(out, (1, 1), 'edge') # erode for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) < 255*4: out[y-1, x-1] = 0 return out # Morphology Erode def Morphology_Erode(img, Dil_time=1): H, W = img.shape # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each dilate time out = img.copy() for i in range(Dil_time): tmp = np.pad(out, (1, 1), 'edge') for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) >= 255: out[y-1, x-1] = 255 return out # Opening morphology def Morphology_Opening(img, time=1): out = Morphology_Dilate(img, Erode_time=time) out = Morphology_Erode(out, Dil_time=time) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Grayscale gray = BGR2GRAY(img) # Otsu's binarization otsu = otsu_binarization(gray) # Morphology - opening out = Morphology_Opening(otsu, time=1) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
248
MIT
gasyori_100_knocks
pythonを用いて、大津の二値化後に、オープニング処理(N=1)を行え。 オープニング処理とは、モルフォロジー処理の収縮をN回行った後に膨張をN回行う処理である。 オープニング処理により、一つだけ余分に存在する画素などを削除できる。
import cv2 import numpy as np import matplotlib.pyplot as plt # Canny def Canny(img): # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Gaussian filter for grayscale def gaussian_filter(img, K_size=3, sigma=1.3): if len(img.shape) == 3: H, W, C = img.shape gray = False else: img = np.expand_dims(img, axis=-1) H, W, C = img.shape gray = True ## Zero padding pad = K_size // 2 out = np.zeros([H + pad * 2, W + pad * 2, C], dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) ## prepare Kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(-pad, -pad + K_size): for y in range(-pad, -pad + K_size): K[y + pad, x + pad] = np.exp( - (x ** 2 + y ** 2) / (2 * sigma * sigma)) #K /= (sigma * np.sqrt(2 * np.pi)) K /= (2 * np.pi * sigma * sigma) K /= K.sum() tmp = out.copy() # filtering for y in range(H): for x in range(W): for c in range(C): out[pad + y, pad + x, c] = np.sum(K * tmp[y : y + K_size, x : x + K_size, c]) out = np.clip(out, 0, 255) out = out[pad : pad + H, pad : pad + W] out = out.astype(np.uint8) if gray: out = out[..., 0] return out # sobel filter def sobel_filter(img, K_size=3): if len(img.shape) == 3: H, W, C = img.shape else: H, W = img.shape # Zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad : pad + H, pad : pad + W] = img.copy().astype(np.float) tmp = out.copy() out_v = out.copy() out_h = out.copy() ## Sobel vertical Kv = [[1., 2., 1.],[0., 0., 0.], [-1., -2., -1.]] ## Sobel horizontal Kh = [[1., 0., -1.],[2., 0., -2.],[1., 0., -1.]] # filtering for y in range(H): for x in range(W): out_v[pad + y, pad + x] = np.sum(Kv * (tmp[y : y + K_size, x : x + K_size])) out_h[pad + y, pad + x] = np.sum(Kh * (tmp[y : y + K_size, x : x + K_size])) out_v = np.clip(out_v, 0, 255) out_h = np.clip(out_h, 0, 255) out_v = out_v[pad : pad + H, pad : pad + W] out_v = out_v.astype(np.uint8) out_h = out_h[pad : pad + H, pad : pad + W] out_h = out_h.astype(np.uint8) return out_v, out_h def get_edge_angle(fx, fy): # get edge strength edge = np.sqrt(np.power(fx.astype(np.float32), 2) + np.power(fy.astype(np.float32), 2)) edge = np.clip(edge, 0, 255) fx = np.maximum(fx, 1e-10) #fx[np.abs(fx) <= 1e-5] = 1e-5 # get edge angle angle = np.arctan(fy / fx) return edge, angle def angle_quantization(angle): angle = angle / np.pi * 180 angle[angle < -22.5] = 180 + angle[angle < -22.5] _angle = np.zeros_like(angle, dtype=np.uint8) _angle[np.where(angle <= 22.5)] = 0 _angle[np.where((angle > 22.5) & (angle <= 67.5))] = 45 _angle[np.where((angle > 67.5) & (angle <= 112.5))] = 90 _angle[np.where((angle > 112.5) & (angle <= 157.5))] = 135 return _angle def non_maximum_suppression(angle, edge): H, W = angle.shape _edge = edge.copy() for y in range(H): for x in range(W): if angle[y, x] == 0: dx1, dy1, dx2, dy2 = -1, 0, 1, 0 elif angle[y, x] == 45: dx1, dy1, dx2, dy2 = -1, 1, 1, -1 elif angle[y, x] == 90: dx1, dy1, dx2, dy2 = 0, -1, 0, 1 elif angle[y, x] == 135: dx1, dy1, dx2, dy2 = -1, -1, 1, 1 if x == 0: dx1 = max(dx1, 0) dx2 = max(dx2, 0) if x == W-1: dx1 = min(dx1, 0) dx2 = min(dx2, 0) if y == 0: dy1 = max(dy1, 0) dy2 = max(dy2, 0) if y == H-1: dy1 = min(dy1, 0) dy2 = min(dy2, 0) if max(max(edge[y, x], edge[y + dy1, x + dx1]), edge[y + dy2, x + dx2]) != edge[y, x]: _edge[y, x] = 0 return _edge def hysterisis(edge, HT=100, LT=30): H, W = edge.shape # Histeresis threshold edge[edge >= HT] = 255 edge[edge <= LT] = 0 _edge = np.zeros((H + 2, W + 2), dtype=np.float32) _edge[1 : H + 1, 1 : W + 1] = edge ## 8 - Nearest neighbor nn = np.array(((1., 1., 1.), (1., 0., 1.), (1., 1., 1.)), dtype=np.float32) for y in range(1, H+2): for x in range(1, W+2): if _edge[y, x] < LT or _edge[y, x] > HT: continue if np.max(_edge[y-1:y+2, x-1:x+2] * nn) >= HT: _edge[y, x] = 255 else: _edge[y, x] = 0 edge = _edge[1:H+1, 1:W+1] return edge # grayscale gray = BGR2GRAY(img) # gaussian filtering gaussian = gaussian_filter(gray, K_size=5, sigma=1.4) # sobel filtering fy, fx = sobel_filter(gaussian, K_size=3) # get edge strength, angle edge, angle = get_edge_angle(fx, fy) # angle quantization angle = angle_quantization(angle) # non maximum suppression edge = non_maximum_suppression(angle, edge) # hysterisis threshold out = hysterisis(edge, 50, 20) return out # Morphology Dilate def Morphology_Dilate(img, Erode_time=1): H, W = img.shape out = img.copy() # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each erode for i in range(Erode_time): tmp = np.pad(out, (1, 1), 'edge') # erode for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) < 255*4: out[y-1, x-1] = 0 return out # Morphology Erode def Morphology_Erode(img, Dil_time=1): H, W = img.shape # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each dilate time out = img.copy() for i in range(Dil_time): tmp = np.pad(out, (1, 1), 'edge') for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) >= 255: out[y-1, x-1] = 255 return out # Morphology Closing def Morphology_Closing(img, time=1): out = Morphology_Erode(img, Dil_time=time) out = Morphology_Dilate(out, Erode_time=time) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Canny canny = Canny(img) # Morphology - opening out = Morphology_Closing(canny, time=1) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
249
MIT
gasyori_100_knocks
pythonを用いて、Canny検出した後に、クロージング処理(N=1)を行え。 クロージング処理とは、モルフォロジー処理の膨張をN回行った後に収縮をN回行う処理である。 クロージング処理により、途中で途切れた画素を結合することができる。
import cv2 import numpy as np import matplotlib.pyplot as plt # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Otsu Binalization def otsu_binarization(img, th=128): H, W = img.shape out = img.copy() max_sigma = 0 max_t = 0 # determine threshold for _t in range(1, 255): v0 = out[np.where(out < _t)] m0 = np.mean(v0) if len(v0) > 0 else 0. w0 = len(v0) / (H * W) v1 = out[np.where(out >= _t)] m1 = np.mean(v1) if len(v1) > 0 else 0. w1 = len(v1) / (H * W) sigma = w0 * w1 * ((m0 - m1) ** 2) if sigma > max_sigma: max_sigma = sigma max_t = _t # Binarization print("threshold >>", max_t) th = max_t out[out < th] = 0 out[out >= th] = 255 return out # Erosion def Erode(img, Erode_time=1): H, W = img.shape out = img.copy() # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each erode for i in range(Erode_time): tmp = np.pad(out, (1, 1), 'edge') # erode for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) < 255*4: out[y-1, x-1] = 0 return out # Dilation def Dilate(img, Dil_time=1): H, W = img.shape # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each dilate time out = img.copy() for i in range(Dil_time): tmp = np.pad(out, (1, 1), 'edge') for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) >= 255: out[y-1, x-1] = 255 return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Grayscale gray = BGR2GRAY(img) # Otsu's binarization otsu = otsu_binarization(gray) # Erode image eroded = Erode(otsu) # Delate image dilated = Dilate(otsu) # Morphology out = np.abs(eroded - dilated) * 255 # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
250
MIT
gasyori_100_knocks
pythonを用いて、大津の二値化を行った後、モルフォロジー勾配を求めよ。 モルフォロジー勾配とはモルフォロジー膨張の画像と収縮の画像の差分をとることで、物体の境界線を抽出する手法である。 ここではモルフォロジー処理のN=1とする。
import cv2 import numpy as np import matplotlib.pyplot as plt # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Otsu Binalization def otsu_binarization(img, th=128): H, W = img.shape out = img.copy() max_sigma = 0 max_t = 0 # determine threshold for _t in range(1, 255): v0 = out[np.where(out < _t)] m0 = np.mean(v0) if len(v0) > 0 else 0. w0 = len(v0) / (H * W) v1 = out[np.where(out >= _t)] m1 = np.mean(v1) if len(v1) > 0 else 0. w1 = len(v1) / (H * W) sigma = w0 * w1 * ((m0 - m1) ** 2) if sigma > max_sigma: max_sigma = sigma max_t = _t # Binarization print("threshold >>", max_t) th = max_t out[out < th] = 0 out[out >= th] = 255 return out # Erosion def Erode(img, Erode_time=1): H, W = img.shape out = img.copy() # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each erode for i in range(Erode_time): tmp = np.pad(out, (1, 1), 'edge') # erode for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) < 255*4: out[y-1, x-1] = 0 return out # Dilation def Dilate(img, Dil_time=1): H, W = img.shape # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each dilate time out = img.copy() for i in range(Dil_time): tmp = np.pad(out, (1, 1), 'edge') for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) >= 255: out[y-1, x-1] = 255 return out # Opening morphology def Morphology_Opening(img, time=1): dil = Dilate(img, Dil_time=time) erode = Erode(dil, Erode_time=time) return erode # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Grayscale gray = BGR2GRAY(img) # Otsu's binarization otsu = otsu_binarization(gray) # Opening process opened = Morphology_Opening(otsu, time=3) # Tophat out = np.abs(otsu - opened) * 255 # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
251
MIT
gasyori_100_knocks
pythonを用いて、大津の二値化を行った後、トップハット変換を行え。 トップハット変換とは元画像からオープニング処理を行った画像を差し引いた画像であり、細い線状のものやノイズなどを抽出できると言われる。 ここでは、大津の二値化画像からオープニング処理画像(N=3)を差し引いて求めよ。
import cv2 import numpy as np import matplotlib.pyplot as plt # Gray scale def BGR2GRAY(img): b = img[:, :, 0].copy() g = img[:, :, 1].copy() r = img[:, :, 2].copy() # Gray scale out = 0.2126 * r + 0.7152 * g + 0.0722 * b out = out.astype(np.uint8) return out # Otsu Binalization def otsu_binarization(img, th=128): H, W = img.shape out = img.copy() max_sigma = 0 max_t = 0 # determine threshold for _t in range(1, 255): v0 = out[np.where(out < _t)] m0 = np.mean(v0) if len(v0) > 0 else 0. w0 = len(v0) / (H * W) v1 = out[np.where(out >= _t)] m1 = np.mean(v1) if len(v1) > 0 else 0. w1 = len(v1) / (H * W) sigma = w0 * w1 * ((m0 - m1) ** 2) if sigma > max_sigma: max_sigma = sigma max_t = _t # Binarization print("threshold >>", max_t) th = max_t out[out < th] = 0 out[out >= th] = 255 return out # Erosion def Erode(img, Erode_time=1): H, W = img.shape out = img.copy() # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each erode for i in range(Erode_time): tmp = np.pad(out, (1, 1), 'edge') # erode for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) < 255*4: out[y-1, x-1] = 0 return out # Dilation def Dilate(img, Dil_time=1): H, W = img.shape # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each dilate time out = img.copy() for i in range(Dil_time): tmp = np.pad(out, (1, 1), 'edge') for y in range(1, H+1): for x in range(1, W+1): if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) >= 255: out[y-1, x-1] = 255 return out # Closing morphology def Morphology_Closing(img, time=1): erode = Erode(img, Erode_time=time) dil = Dilate(erode, Dil_time=time) return erode # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Grayscale gray = BGR2GRAY(img) # Otsu's binarization otsu = otsu_binarization(gray) # Opening process opened = Morphology_Closing(otsu, time=3) # Tophat out = np.abs(opened - otsu) * 255 # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
252
MIT
gasyori_100_knocks
pythonを用いて、大津の二値化を行った後、ブラックハット変換を行え。 ブラックハット変換とはクロージング画像から元画像を差し引いた画像であり、これもトップ変換同様に細い線状やノイズを抽出できると言われる。 ここでは、クロージング処理画像(N=3)から大津の二値化画像を差し引いて求めよ。
import cv2 import numpy as np import matplotlib.pyplot as plt # template matching def Template_matching(img, template): # get original image shape H, W, C = img.shape # get template image shape Ht, Wt, Ct = template.shape # Templete matching # prepare x, y index i, j = -1, -1 # prepare evaluate value v = 255 * H * W * C for y in range(H - Ht): for x in range(W - Wt): # get SSD value _v = np.sum((img[y : y + Ht, x : x + Wt] - template) ** 2) # if SSD is min if _v < v: v = _v i, j = x, y out = img.copy() # draw rectangle cv2.rectangle(out, pt1=(i, j), pt2=(i+Wt, j+Ht), color=(0,0,255), thickness=1) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Read templete image template = cv2.imread("imori_part.jpg").astype(np.float32) # Template matching out = Template_matching(img, template) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
253
MIT
gasyori_100_knocks
pythonを用いて、かつテンプレートマッチングのSSDを用いて、imori_part.jpgがimori.jpgのどこに位置するかをimori.jpgの赤の矩形で図示せよ。 テンプレートマッチングとは、テンプレート画像と全体画像の一部分で類似度が高い位置を探す手法であり、物体検出などで使われる。今では物体検出はCNNで行われるが、テンプレートマッチングは最も基本処理となる。 アルゴリズムとしては、画像I (H x W)、テンプレート画像T (h x w)とすると、 1. 画像Iにおいて、for ( j = 0, H-h) for ( i = 0, W-w)と1ピクセルずつずらしながら画像Aの一部分I(i:i+w, j:j+h)とテンプレート画像の類似度Sを計算する。 2. Sが最大もしくは最小の位置がマッチング位置となる。 Sの選び方は主にSSD, SAD(Q.55), NCC(Q.56), ZNCC(Q.57)などがあり、それぞれ最大値をとるか最小値をとるか異なる。 ここではSSD(Sum of Squared Difference)を用いる。 SSDとは画素値の差分の二乗値の和を類似度にする手法であり、Sが最小の位置がマッチング位置となる。
import cv2 import numpy as np import matplotlib.pyplot as plt # template matching def Template_matching(img, template): # get original image shape H, W, C = img.shape # get template image shape Ht, Wt, Ct = template.shape # Templete matching # prepare x, y index i, j = -1, -1 # prepare evaluate value v = 255 * H * W * C for y in range(H - Ht): for x in range(W - Wt): # get SAD value _v = np.sum(np.abs(img[y : y + Ht, x : x + Wt] - template)) # if SAD is min if _v < v: v = _v i, j = x, y out = img.copy() # draw rectangle cv2.rectangle(out, pt1=(i, j), pt2=(i+Wt, j+Ht), color=(0,0,255), thickness=1) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Read templete image template = cv2.imread("imori_part.jpg").astype(np.float32) # Template matching out = Template_matching(img, template) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
254
MIT
gasyori_100_knocks
pythonを用いて、かつテンプレートマッチングのSADを用いて、imori_part.jpgがimori.jpgのどこに位置するかをimori.jpgの赤の矩形で図示せよ。 SAD(Sum of Absolute Difference)とは画素値の差分の絶対値の和を類似度にする手法であり、Sが最小の位置がマッチング位置となる。 S = Sum_{x=0:w, y=0:h} |I(i+x, j+y) - T(x, y)|
import cv2 import numpy as np import matplotlib.pyplot as plt # template matching def Template_matching(img, template): # get original image shape H, W, C = img.shape # get template image shape Ht, Wt, Ct = template.shape # Templete matching # prepare x, y index i, j = -1, -1 # prepare evaluate value v = -1 for y in range(H - Ht): for x in range(W - Wt): # get NCC value # get numerator of NCC _v = np.sum(img[y : y + Ht, x : x + Wt] * template) # devided numerator _v /= (np.sqrt(np.sum(img[y : y + Ht, x : x + Wt] ** 2)) * np.sqrt(np.sum(template ** 2))) # if NCC is max if _v > v: v = _v i, j = x, y out = img.copy() # draw rectangle cv2.rectangle(out, pt1=(i, j), pt2=(i+Wt, j+Ht), color=(0,0,255), thickness=1) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Read templete image template = cv2.imread("imori_part.jpg").astype(np.float32) # Template matching out = Template_matching(img, template) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
255
MIT
gasyori_100_knocks
pythonを用いて、かつテンプレートマッチングのNCCを用いて、imori_part.jpgがimori.jpgのどこに位置するかをimori.jpgの赤の矩形で図示せよ。 NCC(Normalized Cross Correlation)とは正規化相互相関を類似度にする手法であり、Sが最大の位置がマッチング位置となる。 Sum_{x=0:w, y=0:h} I(i+x, j+y) * T(x, y) S = ----------------------------------------------------------------------------- Sqrt(Sum_{x=0:w, y=0:h} I(i+x, j+y)^2) * Sqrt(Sum_{x=0:w, y=0:h} T(x, y)^2) このSは、-1<=S<=1をとる。 NCCは照明変化に強いと言われる。
import cv2 import numpy as np import matplotlib.pyplot as plt # template matching def Template_matching(img, template): # get original image shape H, W, C = img.shape # subtract mean BGR _img = img - np.mean(img, axis=(0, 1)) # get template image shape Ht, Wt, Ct = template.shape # subtract mean BGR _template = template - np.mean(img, axis=(0, 1)) # Templete matching # prepare x, y index i, j = -1, -1 # prepare evaluate value v = -1 for y in range(H - Ht): for x in range(W - Wt): # get ZNCC value # get numerator of ZNCC _v = np.sum(_img[y : y + Ht, x : x + Wt] * _template) # devided numerator _v /= (np.sqrt(np.sum(_img[y : y + Ht, x : x + Wt] ** 2)) * np.sqrt(np.sum(template ** 2))) # if ZNCC is max if _v > v: v = _v i, j = x, y out = img.copy() # draw rectangle cv2.rectangle(out, pt1=(i, j), pt2=(i+Wt, j+Ht), color=(0,0,255), thickness=1) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Read templete image template = cv2.imread("imori_part.jpg").astype(np.float32) # Template matching out = Template_matching(img, template) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
256
MIT
gasyori_100_knocks
pythonを用いて、かつテンプレートマッチングのZNCCを用いて、imori_part.jpgがimori.jpgのどこに位置するかをimori.jpgの赤の矩形で図示せよ。 ZNCC(Zero means Normalized Cross Correlation)とは零平均正規化相互相関を類似度にする手法であり、Sが最大の位置がマッチング位置となる。 画像Iの平均値をmi、画像Tの平均値をmtとすると、Sは次式で計算される。(ただし、平均値はRGB成分ごとに減算する) Sum_{x=0:w, y=0:h} (I(i+x, j+y)-mi) * (T(x, y)-mt) S = -------------------------------------------------------------------------------------- Sqrt(Sum_{x=0:w, y=0:h} (I(i+x, j+y)-mi)^2) * Sqrt(Sum_{x=0:w, y=0:h} (T(x, y)-mt)^2) このSは、-1<=S<=1をとる。 ZNCCは平均値を引くことでNCCよりも照明変化に強いと言われる。
import cv2 import numpy as np import matplotlib.pyplot as plt # labeling 4 nearest neighbor def labeling_4nn(img): # get image shape H, W, C = img.shape # prepare label tempolary image label = np.zeros((H, W), dtype=np.int) label[img[..., 0]>0] = 1 # look up table LUT = [0 for _ in range(H*W)] n = 1 for y in range(H): for x in range(W): # skip black pixel if label[y, x] == 0: continue # get above pixel c3 = label[max(y-1,0), x] # get left pixel c5 = label[y, max(x-1,0)] # if not labeled if c3 < 2 and c5 < 2: # labeling n += 1 label[y, x] = n else: # replace min label index _vs = [c3, c5] vs = [a for a in _vs if a > 1] v = min(vs) label[y, x] = v minv = v for _v in vs: if LUT[_v] != 0: minv = min(minv, LUT[_v]) for _v in vs: LUT[_v] = minv count = 1 # integrate index of look up table for l in range(2, n+1): flag = True for i in range(n+1): if LUT[i] == l: if flag: count += 1 flag = False LUT[i] = count # draw color COLORS = [[0, 0, 255], [0, 255, 0], [255, 0, 0], [255, 255, 0]] out = np.zeros((H, W, C), dtype=np.uint8) for i, lut in enumerate(LUT[2:]): out[label == (i+2)] = COLORS[lut-2] return out # Read image img = cv2.imread("seg.png").astype(np.float32) # labeling 4 nearest neighbor out = labeling_4nn(img) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
257
MIT
gasyori_100_knocks
pythonを用いて、seg.pngをラベリングせよ。 ラベリングとは隣接したピクセルに同じラベルを割り当てる作業である。 つまり、 黒 黒 黒 黒 黒 白 白 黒 黒 白 黒 黒 黒 黒 黒 黒 このように隣り合った白ピクセルは同じラベルを割り当てる。 このようにピクセルの塊にラベリングしたものはConnected Componentとも呼ばれる。 ここでは4近傍に注目してラベリングを行う。 また、ここではルックアップテーブルというものを使用する。 ルックアップテーブルとは | Source | Distination | | 1 | 1 | | 2 | 2 | | 3 | 1 | というような表になっており、Source=1に割り当てた画素には最終的にラベル1を割り当てる、Source =3に割り当てた画素には最終的にラベル1を割り当てることを示す表である。 アルゴリズムは 1. 左上からラスタスキャンを行う。 2. 注目画素i(x,y)が黒画素なら何も行わない。白画素なら、上画素i(x,y-1)と左画素i(x-1,y)に注目し、どちらも0だった場合、最後に割り当てたラベル+1を割り当てる。 3. どちらか一方以上が0でない場合(つまりすでにラベルが割り合っている場合)、上と左に割り当てられたラベルの中で最小の方(0以外)をi(x,y)に割り当てる。ここで、上か左で用いなかったラベルに対応するルックアップテーブルをここで割り当てた番号に変える。 4. 最後、ルックアップテーブルを見て、Sourceに対応する画素に当たる部分をDistinationの値に変換する。 以上により隣接ピクセル同士に同じラベルを割り当てる。 4近傍としているが、ラスタスキャンのため、上画素と左画素の2画素に注目すればいい。
import cv2 import numpy as np import matplotlib.pyplot as plt # labeling 8 nearest neighbor def labeling_8nn(img): # get image shape H, W, C = img.shape # prepare labeling image label = np.zeros((H, W), dtype=np.int) label[img[..., 0]>0] = 1 # look up table LUT = [0 for _ in range(H*W)] n = 1 for y in range(H): for x in range(W): if label[y, x] == 0: continue # get right top pixel c2 = label[max(y-1,0), min(x+1, W-1)] # get top pixel c3 = label[max(y-1,0), x] # get left top pixel c4 = label[max(y-1,0), max(x-1,0)] # get left pixel c5 = label[y, max(x-1,0)] # if all pixel is non labeled if c3 < 2 and c5 < 2 and c2 < 2 and c4 < 2: n += 1 label[y, x] = n else: # get labeled index _vs = [c3, c5, c2, c4] vs = [a for a in _vs if a > 1] v = min(vs) label[y, x] = v minv = v for _v in vs: if LUT[_v] != 0: minv = min(minv, LUT[_v]) for _v in vs: LUT[_v] = minv count = 1 # integrate labeled index of look up table for l in range(2, n+1): flag = True for i in range(n+1): if LUT[i] == l: if flag: count += 1 flag = False LUT[i] = count # draw color COLORS = [[0, 0, 255], [0, 255, 0], [255, 0, 0], [255, 255, 0]] out = np.zeros((H, W, C), dtype=np.uint8) for i, lut in enumerate(LUT[2:]): out[label == (i+2)] = COLORS[lut-2] return out # Read image img = cv2.imread("seg.png").astype(np.float32) # labeling 8 nearest neighbor out = labeling_8nn(img) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
258
MIT
gasyori_100_knocks
pythonを用いて、8近傍のラベリングを行え。ラベリングとは隣接したピクセルに同じラベルを割り当てる作業である。 つまり、 黒 黒 黒 黒 黒 白 白 黒 黒 白 黒 黒 黒 黒 黒 黒 このように隣り合った白ピクセルは同じラベルを割り当てる。 このようにピクセルの塊にラベリングしたものはConnected Componentとも呼ばれる。 ここではルックアップテーブルというものを使用する。 ルックアップテーブルとは | Source | Distination | | 1 | 1 | | 2 | 2 | | 3 | 1 | というような表になっており、Source=1に割り当てた画素には最終的にラベル1を割り当てる、Source =3に割り当てた画素には最終的にラベル1を割り当てることを示す表である。 アルゴリズムは 1. 左上からラスタスキャンを行う。 2. 注目画素i(x,y)が黒画素なら何も行わない。白画素なら、上画素i(x,y-1)と左画素i(x-1,y)に注目し、どちらも0だった場合、最後に割り当てたラベル+1を割り当てる。 3. どちらか一方以上が0でない場合(つまりすでにラベルが割り合っている場合)、上と左に割り当てられたラベルの中で最小の方(0以外)をi(x,y)に割り当てる。ここで、上か左で用いなかったラベルに対応するルックアップテーブルをここで割り当てた番号に変える。 4. 最後、ルックアップテーブルを見て、Sourceに対応する画素に当たる部分をDistinationの値に変換する。 以上により隣接ピクセル同士に同じラベルを割り当てる。 8近傍とは、i(x-1,y-1), i(x, y-1), i(x+1,y-1), i(x-1,y)の4画素に注目すればよい。
import cv2 import numpy as np import matplotlib.pyplot as plt # alpha blend def alpha_blend(img1, img2, alpha): # blend out = img * alpha + img2 * (1 - alpha) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # Read blend target image img2 = cv2.imread("thorino.jpg").astype(np.float32) out = alpha_blend(img, img2, alpha=0.6) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
259
MIT
gasyori_100_knocks
pythonを用いて、アルファブレンドにより、imori.jpgとthorino.jpgを6:4の割合で画像を合成せよ。 アルファブレンドとは透明度(アルファ値)を設定することにより画像の透明度を設定する方法である。 OpenCVでは透明度のパラメータはないが、PILなどのライブラリでは存在する。 ここではその透明度を手動で設定する。 二つの画像を重ね合わせたい時などに、この手法は有効である。 img1とimg2を1:1の割合で重ね合わせたい時は、次式となる。 alphaの値を変えることで重ねる時の重みを変えることができる。 alpha = 0.5 out = img1 * alpha + img2 * (1 - alpha)
import cv2 import numpy as np import matplotlib.pyplot as plt # Connect 4 def connect_4(img): # get shape H, W, C = img.shape # prepare temporary image tmp = np.zeros((H, W), dtype=np.int) # binarize tmp[img[..., 0] > 0] = 1 # prepare out image out = np.zeros((H, W, 3), dtype=np.uint8) # each pixel for y in range(H): for x in range(W): if tmp[y, x] < 1: continue S = 0 S += (tmp[y,min(x+1,W-1)] - tmp[y,min(x+1,W-1)] * tmp[max(y-1,0),min(x+1,W-1)] * tmp[max(y-1,0),x]) S += (tmp[max(y-1,0),x] - tmp[max(y-1,0),x] * tmp[max(y-1,0),max(x-1,0)] * tmp[y,max(x-1,0)]) S += (tmp[y,max(x-1,0)] - tmp[y,max(x-1,0)] * tmp[min(y+1,H-1),max(x-1,0)] * tmp[min(y+1,H-1),x]) S += (tmp[min(y+1,H-1),x] - tmp[min(y+1,H-1),x] * tmp[min(y+1,H-1),min(x+1,W-1)] * tmp[y,min(x+1,W-1)]) if S == 0: out[y,x] = [0, 0, 255] elif S == 1: out[y,x] = [0, 255, 0] elif S == 2: out[y,x] = [255, 0, 0] elif S == 3: out[y,x] = [255, 255, 0] elif S == 4: out[y,x] = [255, 0, 255] out = out.astype(np.uint8) return out # Read image img = cv2.imread("renketsu.png").astype(np.float32) # connect 4 out = connect_4(img) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
260
MIT
gasyori_100_knocks
pythonを用いて、renketsu.pngを4-連結数により、色分けせよ。 4-連結数とは近傍との画素の状態を見る値である。 通常、近傍は注目画素x0(x,y)が0でない場合に対して、次のように定義される。 x4(x-1,y-1) x3(x,y-1) x2(x+1,y-1) x5(x-1,y) x0(x,y) x1(x+1,y) x6(x-1,y+1) x7(x,y+1) x8(x+1,y+1) ここで4連結数とは、次式で計算される。 S = (x1 - x1 x2 x3) + (x3 - x3 x4 x5) + (x5 - x5 x6 x7) + (x7 - x7 x8 x1) S = [0,4]の範囲をとり、 - S = 0 は内部点 - S = 1 は端点 - S = 2 は連結点 - S = 3 は分岐点 - S = 4 は交差点 を示す。
import cv2 import numpy as np import matplotlib.pyplot as plt # connect 8 def connect_8(img): # get shape H, W, C = img.shape # prepare temporary _tmp = np.zeros((H, W), dtype=np.int) # get binarize _tmp[img[..., 0] > 0] = 1 # inverse for connect 8 tmp = 1 - _tmp # prepare image out = np.zeros((H, W, 3), dtype=np.uint8) # each pixel for y in range(H): for x in range(W): if _tmp[y, x] < 1: continue S = 0 S += (tmp[y,min(x+1,W-1)] - tmp[y,min(x+1,W-1)] * tmp[max(y-1,0),min(x+1,W-1)] * tmp[max(y-1,0),x]) S += (tmp[max(y-1,0),x] - tmp[max(y-1,0),x] * tmp[max(y-1,0),max(x-1,0)] * tmp[y,max(x-1,0)]) S += (tmp[y,max(x-1,0)] - tmp[y,max(x-1,0)] * tmp[min(y+1,H-1),max(x-1,0)] * tmp[min(y+1,H-1),x]) S += (tmp[min(y+1,H-1),x] - tmp[min(y+1,H-1),x] * tmp[min(y+1,H-1),min(x+1,W-1)] * tmp[y,min(x+1,W-1)]) if S == 0: out[y,x] = [0, 0, 255] elif S == 1: out[y,x] = [0, 255, 0] elif S == 2: out[y,x] = [255, 0, 0] elif S == 3: out[y,x] = [255, 255, 0] elif S == 4: out[y,x] = [255, 0, 255] out = out.astype(np.uint8) return out # Read image img = cv2.imread("renketsu.png").astype(np.float32) # connect 8 out = connect_8(img) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
261
MIT
gasyori_100_knocks
pythonを用いて、renketsu.pngを8-連結数により、色分けせよ。 8連結数とは S = (x1 - x1 x2 x3) + (x3 - x3 x4 x5) + (x5 - x5 x6 x7) + (x7 - x7 x8 x1) において各x¥*の値の0と1を反転させた値を用いる。
import cv2 import numpy as np import matplotlib.pyplot as plt # thining algorythm def thining(img): # get shape H, W, C = img.shape # prepare out image out = np.zeros((H, W), dtype=np.int) out[img[..., 0] > 0] = 1 count = 1 while count > 0: count = 0 tmp = out.copy() # each pixel ( rasta scan ) for y in range(H): for x in range(W): # skip black pixel if out[y, x] < 1: continue # count satisfied conditions judge = 0 ## condition 1 if (tmp[y, min(x+1, W-1)] + tmp[max(y-1, 0), x] + tmp[y, max(x-1, 0)] + tmp[min(y+1, H-1), x]) < 4: judge += 1 ## condition 2 c = 0 c += (tmp[y,min(x+1, W-1)] - tmp[y, min(x+1, W-1)] * tmp[max(y-1, 0),min(x+1, W-1)] * tmp[max(y-1, 0), x]) c += (tmp[max(y-1,0), x] - tmp[max(y-1,0), x] * tmp[max(y-1, 0), max(x-1, 0)] * tmp[y, max(x-1, 0)]) c += (tmp[y, max(x-1, 0)] - tmp[y,max(x-1, 0)] * tmp[min(y+1, H-1), max(x-1, 0)] * tmp[min(y+1, H-1), x]) c += (tmp[min(y+1, H-1), x] - tmp[min(y+1, H-1), x] * tmp[min(y+1, H-1), min(x+1, W-1)] * tmp[y, min(x+1, W-1)]) if c == 1: judge += 1 ##x condition 3 if np.sum(tmp[max(y-1, 0) : min(y+2, H), max(x-1, 0) : min(x+2, W)]) >= 4: judge += 1 # if all conditions are satisfied if judge == 3: out[y, x] = 0 count += 1 out = out.astype(np.uint8) * 255 return out # Read image img = cv2.imread("gazo.png").astype(np.float32) # thining out = thining(img) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
262
MIT
gasyori_100_knocks
pythonを用いて、gazo.pngを細線化せよ。 細線化とは画素の幅を1にする処理であり、ここでは次のアルゴリズムに沿って処理を行え。 1. 左上からラスタスキャンする。 2. x0(x,y)=0ならば、処理なし。x0(x,y)=1ならば次の3条件を満たす時にx0=0に変える。 (1) 注目画素の4近傍に0が一つ以上存在する (2) x0の4-連結数が1である (3) x0の8近傍に1が3つ以上存在する 3. 一回のラスタスキャンで2の変更数が0になるまで、ラスタスキャンを繰り返す。 細線化にはヒルディッチのアルゴリズム(Q.64)や、Zhang-Suenのアルゴリズム(Q.65)、田村のアルゴリズムなどが存在する。
import cv2 import numpy as np import matplotlib.pyplot as plt # hilditch thining def hilditch(img): # get shape H, W, C = img.shape # prepare out image out = np.zeros((H, W), dtype=np.int) out[img[..., 0] > 0] = 1 # inverse pixel value tmp = out.copy() _tmp = 1 - tmp count = 1 while count > 0: count = 0 tmp = out.copy() _tmp = 1 - tmp tmp2 = out.copy() _tmp2 = 1 - tmp2 # each pixel for y in range(H): for x in range(W): # skip black pixel if out[y, x] < 1: continue judge = 0 ## condition 1 if (tmp[y, min(x+1, W-1)] * tmp[max(y-1,0 ), x] * tmp[y, max(x-1, 0)] * tmp[min(y+1, H-1), x]) == 0: judge += 1 ## condition 2 c = 0 c += (_tmp[y, min(x+1, W-1)] - _tmp[y, min(x+1, W-1)] * _tmp[max(y-1, 0), min(x+1, W-1)] * _tmp[max(y-1, 0), x]) c += (_tmp[max(y-1, 0), x] - _tmp[max(y-1, 0), x] * _tmp[max(y-1, 0), max(x-1, 0)] * _tmp[y, max(x-1, 0)]) c += (_tmp[y, max(x-1, 0)] - _tmp[y, max(x-1, 0)] * _tmp[min(y+1, H-1), max(x-1, 0)] * _tmp[min(y+1, H-1), x]) c += (_tmp[min(y+1, H-1), x] - _tmp[min(y+1, H-1), x] * _tmp[min(y+1, H-1), min(x+1, W-1)] * _tmp[y, min(x+1, W-1)]) if c == 1: judge += 1 ## condition 3 if np.sum(tmp[max(y-1, 0) : min(y+2, H), max(x-1, 0) : min(x+2, W)]) >= 3: judge += 1 ## condition 4 if np.sum(out[max(y-1, 0) : min(y+2, H), max(x-1, 0) : min(x+2, W)]) >= 2: judge += 1 ## condition 5 _tmp2 = 1 - out c = 0 c += (_tmp2[y, min(x+1, W-1)] - _tmp2[y, min(x+1, W-1)] * _tmp2[max(y-1, 0), min(x+1, W-1)] * _tmp2[max(y-1, 0), x]) c += (_tmp2[max(y-1, 0), x] - _tmp2[max(y-1, 0), x] * (1 - tmp[max(y-1, 0), max(x-1, 0)]) * _tmp2[y, max(x-1, 0)]) c += (_tmp2[y, max(x-1, 0)] - _tmp2[y, max(x-1, 0)] * _tmp2[min(y+1, H-1), max(x-1, 0)] * _tmp2[min(y+1, H-1), x]) c += (_tmp2[min(y+1, H-1), x] - _tmp2[min(y+1, H-1), x] * _tmp2[min(y+1, H-1), min(x+1, W-1)] * _tmp2[y, min(x+1, W-1)]) if c == 1 or (out[max(y-1, 0), max(x-1,0 )] != tmp[max(y-1, 0), max(x-1, 0)]): judge += 1 c = 0 c += (_tmp2[y, min(x+1, W-1)] - _tmp2[y, min(x+1, W-1)] * _tmp2[max(y-1, 0), min(x+1, W-1)] * (1 - tmp[max(y-1, 0), x])) c += ((1-tmp[max(y-1, 0), x]) - (1 - tmp[max(y-1, 0), x]) * _tmp2[max(y-1, 0), max(x-1, 0)] * _tmp2[y, max(x-1, 0)]) c += (_tmp2[y, max(x-1,0 )] - _tmp2[y, max(x-1,0 )] * _tmp2[min(y+1, H-1), max(x-1, 0)] * _tmp2[min(y+1, H-1), x]) c += (_tmp2[min(y+1, H-1), x] - _tmp2[min(y+1, H-1), x] * _tmp2[min(y+1, H-1), min(x+1, W-1)] * _tmp2[y, min(x+1, W-1)]) if c == 1 or (out[max(y-1, 0), x] != tmp[max(y-1, 0), x]): judge += 1 c = 0 c += (_tmp2[y, min(x+1, W-1)] - _tmp2[y, min(x+1, W-1)] * (1 - tmp[max(y-1, 0), min(x+1, W-1)]) * _tmp2[max(y-1, 0), x]) c += (_tmp2[max(y-1, 0), x] - _tmp2[max(y-1, 0), x] * _tmp2[max(y-1, 0), max(x-1, 0)] * _tmp2[y, max(x-1, 0)]) c += (_tmp2[y, max(x-1, 0)] - _tmp2[y, max(x-1, 0)] * _tmp2[min(y+1, H-1), max(x-1, 0)] * _tmp2[min(y+1, H-1), x]) c += (_tmp2[min(y+1, H-1), x] - _tmp2[min(y+1, H-1), x] * _tmp2[min(y+1, H-1), min(x+1, W-1)] * _tmp2[y, min(x+1, W-1)]) if c == 1 or (out[max(y-1, 0), min(x+1, W-1)] != tmp[max(y-1, 0), min(x+1, W-1)]): judge += 1 c = 0 c += (_tmp2[y, min(x+1, W-1)] - _tmp2[y, min(x+1, W-1)] * _tmp2[max(y-1, 0), min(x+1, W-1)] * _tmp2[max(y-1, 0), x]) c += (_tmp2[max(y-1, 0), x] - _tmp2[max(y-1, 0), x] * _tmp2[max(y-1, 0), max(x-1, 0)] * (1 - tmp[y, max(x-1, 0)])) c += ((1 - tmp[y, max(x-1, 0)]) - (1 - tmp[y, max(x-1, 0)]) * _tmp2[min(y+1, H-1), max(x-1, 0)] * _tmp2[min(y+1, H-1), x]) c += (_tmp2[min(y+1, H-1), x] - _tmp2[min(y+1, H-1), x] * _tmp2[min(y+1, H-1), min(x+1, W-1)] * _tmp2[y, min(x+1, W-1)]) if c == 1 or (out[y, max(x-1, 0)] != tmp[y, max(x-1, 0)]): judge += 1 if judge >= 8: out[y, x] = 0 count += 1 out = out.astype(np.uint8) * 255 return out # Read image img = cv2.imread("gazo.png").astype(np.float32) # hilditch thining out = hilditch(img) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
263
MIT
gasyori_100_knocks
pythonを用いて、gazo.pngにヒルディッチの細線化を行え。 アルゴリズムは、次の通り。 1. 左上からラスタスキャンする。 2. x0(x,y)=0ならば、処理なし。x0(x,y)=1ならば次の5条件を満たす時にx0=-1に変える。 1. 注目画素の4近傍に0が一つ以上存在する 2. x0の8-連結数が1である 3. x1〜x8の絶対値の合計が2以上 4. x0の8近傍に1が1つ以上存在する 5. xn(n=1〜8)全てに対して以下のどちらかが成り立つ - xnが-1以外 - xnを0とした時、x0の8-連結数が1である 3. 各画素の-1を0に変える 4. 一回のラスタスキャンで3の変更数が0になるまで、ラスタスキャンを繰り返す。
import cv2 import numpy as np import matplotlib.pyplot as plt # Zhang Suen thining algorythm def Zhang_Suen_thining(img): # get shape H, W, C = img.shape # prepare out image out = np.zeros((H, W), dtype=np.int) out[img[..., 0] > 0] = 1 # inverse out = 1 - out while True: s1 = [] s2 = [] # step 1 ( rasta scan ) for y in range(1, H-1): for x in range(1, W-1): # condition 1 if out[y, x] > 0: continue # condition 2 f1 = 0 if (out[y-1, x+1] - out[y-1, x]) == 1: f1 += 1 if (out[y, x+1] - out[y-1, x+1]) == 1: f1 += 1 if (out[y+1, x+1] - out[y, x+1]) == 1: f1 += 1 if (out[y+1, x] - out[y+1,x+1]) == 1: f1 += 1 if (out[y+1, x-1] - out[y+1, x]) == 1: f1 += 1 if (out[y, x-1] - out[y+1, x-1]) == 1: f1 += 1 if (out[y-1, x-1] - out[y, x-1]) == 1: f1 += 1 if (out[y-1, x] - out[y-1, x-1]) == 1: f1 += 1 if f1 != 1: continue # condition 3 f2 = np.sum(out[y-1:y+2, x-1:x+2]) if f2 < 2 or f2 > 6: continue # condition 4 if out[y-1, x] + out[y, x+1] + out[y+1, x] < 1: continue # condition 5 if out[y, x+1] + out[y+1, x] + out[y, x-1] < 1: continue s1.append([y, x]) for v in s1: out[v[0], v[1]] = 1 # step 2 ( rasta scan ) for y in range(1, H-1): for x in range(1, W-1): # condition 1 if out[y, x] > 0: continue # condition 2 f1 = 0 if (out[y-1, x+1] - out[y-1, x]) == 1: f1 += 1 if (out[y, x+1] - out[y-1, x+1]) == 1: f1 += 1 if (out[y+1, x+1] - out[y, x+1]) == 1: f1 += 1 if (out[y+1, x] - out[y+1,x+1]) == 1: f1 += 1 if (out[y+1, x-1] - out[y+1, x]) == 1: f1 += 1 if (out[y, x-1] - out[y+1, x-1]) == 1: f1 += 1 if (out[y-1, x-1] - out[y, x-1]) == 1: f1 += 1 if (out[y-1, x] - out[y-1, x-1]) == 1: f1 += 1 if f1 != 1: continue # condition 3 f2 = np.sum(out[y-1:y+2, x-1:x+2]) if f2 < 2 or f2 > 6: continue # condition 4 if out[y-1, x] + out[y, x+1] + out[y, x-1] < 1: continue # condition 5 if out[y-1, x] + out[y+1, x] + out[y, x-1] < 1: continue s2.append([y, x]) for v in s2: out[v[0], v[1]] = 1 # if not any pixel is changed if len(s1) < 1 and len(s2) < 1: break out = 1 - out out = out.astype(np.uint8) * 255 return out # Read image img = cv2.imread("gazo.png").astype(np.float32) # Zhang Suen thining out = Zhang_Suen_thining(img) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
264
MIT
gasyori_100_knocks
pythonを用いて、gazo.pngにZhang-Suenの細線化を行え。 ただし、以下の操作は全て0が線、1が背景とするので、*gazo.png*の値を反転させる必要があることに注意。 注目画素x1(x,y)に対して8近傍を次のように定義する。 x9 x2 x3 x8 x1 x4 x7 x6 x5 これらに対して二つのステップを考える。 Step.1 ラスタスキャンを行い、以下の5条件を満たすピクセルを全て記録する。 1. 黒画素である 2. x2, x3, ..., x9, x2と時計まわりに見て、0から1に変わる回数がちょうど1 3. x2, x3, ..., x9の中で1の個数が2以上6以下 4. x2, x4, x6のどれかが1 5. x4, x6, x8のどれかが1 記録したピクセルを全て1に変更する。 Step.2 ラスタスキャンを行い、以下の5条件を満たすピクセルを全て記録する。 1. 黒画素である 2. x2, x3, ..., x9, x2と時計まわりに見て、0から1に変わる回数がちょうど1 3. x2, x3, ..., x9の中で1の個数が2以上6以下 4. x2, x4, x8のどれかが1 5. x2, x6, x8のどれかが1 記録したピクセルを全て1に変更する。 Step1, 2で変更する点がなくなるまで交互に繰り返す。
import cv2 import numpy as np import matplotlib.pyplot as plt # get HOG step1 def HOG_step1(img): # Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Magnitude and gradient def get_gradXY(gray): H, W = gray.shape # padding before grad gray = np.pad(gray, (1, 1), 'edge') # get grad x gx = gray[1:H+1, 2:] - gray[1:H+1, :W] # get grad y gy = gray[2:, 1:W+1] - gray[:H, 1:W+1] # replace 0 with gx[gx == 0] = 1e-6 return gx, gy # get magnitude and gradient def get_MagGrad(gx, gy): # get gradient maginitude magnitude = np.sqrt(gx ** 2 + gy ** 2) # get gradient angle gradient = np.arctan(gy / gx) gradient[gradient < 0] = np.pi / 2 + gradient[gradient < 0] + np.pi / 2 return magnitude, gradient # Gradient histogram def quantization(gradient): # prepare quantization table gradient_quantized = np.zeros_like(gradient, dtype=np.int) # quantization base d = np.pi / 9 # quantization for i in range(9): gradient_quantized[np.where((gradient >= d * i) & (gradient <= d * (i + 1)))] = i return gradient_quantized # 1. BGR -> Gray gray = BGR2GRAY(img) # 1. Gray -> Gradient x and y gx, gy = get_gradXY(gray) # 2. get gradient magnitude and angle magnitude, gradient = get_MagGrad(gx, gy) # 3. Quantization gradient_quantized = quantization(gradient) return magnitude, gradient_quantized # Read image img = cv2.imread("imori.jpg").astype(np.float32) # get HOG step1 magnitude, gradient_quantized = HOG_step1(img) # Write gradient magnitude to file _magnitude = (magnitude / magnitude.max() * 255).astype(np.uint8) cv2.imwrite("out_mag.jpg", _magnitude) # Write gradient angle to file H, W, C = img.shape out = np.zeros((H, W, 3), dtype=np.uint8) # define color C = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [255, 0, 255], [0, 255, 255], [127, 127, 0], [127, 0, 127], [0, 127, 127]] # draw color for i in range(9): out[gradient_quantized == i] = C[i] cv2.imwrite("out_gra.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
265
MIT
gasyori_100_knocks
pythonを用いて、imoir.jpgのHOG特徴量の勾配強度・勾配角度を求めよ。 HOG(Histogram of Oriented Gradients)とは画像の特徴量表現の一種である。 特徴量とは画像の状態などを表すベクトル集合のことである。 画像認識(画像が何を写した画像か)や検出(画像の中で物体がどこにあるか)では、(1)画像から特徴量を得て(特徴抽出)、(2)特徴量を基に認識や検出を行う(認識・検出)。 ディープラーニングでは特徴抽出から認識までを機械学習により自動で行うため、HOGなどは見られなくなっているが、ディープラーニングが流行る前まではHOGは特徴量表現としてよく使われたらしい。 HOGは以下のアルゴリズムで得られる。 1. 画像をグレースケール化し、x、y方向の輝度勾配を求める x方向: gx = I(x+1, y) - I(x-1, y) y方向: gy = I(x, y+1) - I(x, y-1) 2. gx, gyから勾配強度と勾配角度を求める。 勾配強度: mag = sqrt(gt 2 + gy 2) 勾配角度: ang = arctan(gy / gx) 3. 勾配角度を [0, 180]で9分割した値に量子化する。つまり、[0,20]には0、[20, 40]には1というインデックスを求める。 4. 画像をN x Nの領域に分割し(この領域をセルという)、セル内で3で求めたインデックスのヒストグラムを作成する。ただし、当表示は1でなく勾配角度を求める。 5. C x Cのセルを1つとして(これをブロックという)、ブロック内のセルのヒストグラムを次式で正規化する。これを1セルずつずらしながら行うので、一つのセルが何回も正規化される。
import cv2 import numpy as np import matplotlib.pyplot as plt # get HOG step2 def HOG_step2(img): # Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Magnitude and gradient def get_gradXY(gray): H, W = gray.shape # padding before grad gray = np.pad(gray, (1, 1), 'edge') # get grad x gx = gray[1:H+1, 2:] - gray[1:H+1, :W] # get grad y gy = gray[2:, 1:W+1] - gray[:H, 1:W+1] # replace 0 with gx[gx == 0] = 1e-6 return gx, gy # get magnitude and gradient def get_MagGrad(gx, gy): # get gradient maginitude magnitude = np.sqrt(gx ** 2 + gy ** 2) # get gradient angle gradient = np.arctan(gy / gx) gradient[gradient < 0] = np.pi / 2 + gradient[gradient < 0] + np.pi / 2 return magnitude, gradient # Gradient histogram def quantization(gradient): # prepare quantization table gradient_quantized = np.zeros_like(gradient, dtype=np.int) # quantization base d = np.pi / 9 # quantization for i in range(9): gradient_quantized[np.where((gradient >= d * i) & (gradient <= d * (i + 1)))] = i return gradient_quantized # get gradient histogram def gradient_histogram(gradient_quantized, magnitude, N=8): # get shape H, W = magnitude.shape # get cell num cell_N_H = H // N cell_N_W = W // N histogram = np.zeros((cell_N_H, cell_N_W, 9), dtype=np.float32) # each pixel for y in range(cell_N_H): for x in range(cell_N_W): for j in range(N): for i in range(N): histogram[y, x, gradient_quantized[y * 4 + j, x * 4 + i]] += magnitude[y * 4 + j, x * 4 + i] return histogram # 1. BGR -> Gray gray = BGR2GRAY(img) # 1. Gray -> Gradient x and y gx, gy = get_gradXY(gray) # 2. get gradient magnitude and angle magnitude, gradient = get_MagGrad(gx, gy) # 3. Quantization gradient_quantized = quantization(gradient) # 4. Gradient histogram histogram = gradient_histogram(gradient_quantized, magnitude) return histogram # Read image img = cv2.imread("imori.jpg").astype(np.float32) # get HOG step2 histogram = HOG_step2(img) # write histogram to file for i in range(9): plt.subplot(3,3,i+1) plt.imshow(histogram[..., i]) plt.axis('off') plt.xticks(color="None") plt.yticks(color="None") plt.savefig("out.png") plt.show()
code_generation
266
MIT
gasyori_100_knocks
HOGは以下のアルゴリズムで得られる。 1. 画像をグレースケール化し、x、y方向の輝度勾配を求める x方向: gx = I(x+1, y) - I(x-1, y) y方向: gy = I(x, y+1) - I(x, y-1) 2. gx, gyから勾配強度と勾配角度を求める。 勾配強度: mag = sqrt(gt 2 + gy 2) 勾配角度: ang = arctan(gy / gx) 3. 勾配角度を [0, 180]で9分割した値に量子化する。つまり、[0,20]には0、[20, 40]には1というインデックスを求める。 4. 画像をN x Nの領域に分割し(この領域をセルという)、セル内で3で求めたインデックスのヒストグラムを作成する。ただし、当表示は1でなく勾配角度を求める。 5. C x Cのセルを1つとして(これをブロックという)、ブロック内のセルのヒストグラムを次式で正規化する。これを1セルずつずらしながら行うので、一つのセルが何回も正規化される。 ここではpythonを用いてHOGの4の処理を実装する。 N=8として、8x8の領域を1セルとして、勾配角度のインデックスに勾配強度を投票する形式でヒストグラムを作成せよ。 解答は 1 2 3 4 5 6 7 8 9 の順に量子化したインデックスに対応するヒストグラムを示す。
import cv2 import numpy as np import matplotlib.pyplot as plt # get HOG def HOG(img): # Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Magnitude and gradient def get_gradXY(gray): H, W = gray.shape # padding before grad gray = np.pad(gray, (1, 1), 'edge') # get grad x gx = gray[1:H+1, 2:] - gray[1:H+1, :W] # get grad y gy = gray[2:, 1:W+1] - gray[:H, 1:W+1] # replace 0 with gx[gx == 0] = 1e-6 return gx, gy # get magnitude and gradient def get_MagGrad(gx, gy): # get gradient maginitude magnitude = np.sqrt(gx ** 2 + gy ** 2) # get gradient angle gradient = np.arctan(gy / gx) gradient[gradient < 0] = np.pi / 2 + gradient[gradient < 0] + np.pi / 2 return magnitude, gradient # Gradient histogram def quantization(gradient): # prepare quantization table gradient_quantized = np.zeros_like(gradient, dtype=np.int) # quantization base d = np.pi / 9 # quantization for i in range(9): gradient_quantized[np.where((gradient >= d * i) & (gradient <= d * (i + 1)))] = i return gradient_quantized # get gradient histogram def gradient_histogram(gradient_quantized, magnitude, N=8): # get shape H, W = magnitude.shape # get cell num cell_N_H = H // N cell_N_W = W // N histogram = np.zeros((cell_N_H, cell_N_W, 9), dtype=np.float32) # each pixel for y in range(cell_N_H): for x in range(cell_N_W): for j in range(N): for i in range(N): histogram[y, x, gradient_quantized[y * 4 + j, x * 4 + i]] += magnitude[y * 4 + j, x * 4 + i] return histogram # histogram normalization def normalization(histogram, C=3, epsilon=1): cell_N_H, cell_N_W, _ = histogram.shape ## each histogram for y in range(cell_N_H): for x in range(cell_N_W): #for i in range(9): histogram[y, x] /= np.sqrt(np.sum(histogram[max(y - 1, 0) : min(y + 2, cell_N_H), max(x - 1, 0) : min(x + 2, cell_N_W)] ** 2) + epsilon) return histogram # 1. BGR -> Gray gray = BGR2GRAY(img) # 1. Gray -> Gradient x and y gx, gy = get_gradXY(gray) # 2. get gradient magnitude and angle magnitude, gradient = get_MagGrad(gx, gy) # 3. Quantization gradient_quantized = quantization(gradient) # 4. Gradient histogram histogram = gradient_histogram(gradient_quantized, magnitude) # 5. Histogram normalization histogram = normalization(histogram) return histogram # Read image img = cv2.imread("imori.jpg").astype(np.float32) # get HOG histogram = HOG(img) # Write result to file for i in range(9): plt.subplot(3,3,i+1) plt.imshow(histogram[..., i]) plt.axis('off') plt.xticks(color="None") plt.yticks(color="None") plt.savefig("out.png") plt.show()
code_generation
267
MIT
gasyori_100_knocks
HOGは以下のアルゴリズムで得られる。 1. 画像をグレースケール化し、x、y方向の輝度勾配を求める x方向: gx = I(x+1, y) - I(x-1, y) y方向: gy = I(x, y+1) - I(x, y-1) 2. gx, gyから勾配強度と勾配角度を求める。 勾配強度: mag = sqrt(gt 2 + gy 2) 勾配角度: ang = arctan(gy / gx) 3. 勾配角度を [0, 180]で9分割した値に量子化する。つまり、[0,20]には0、[20, 40]には1というインデックスを求める。 4. 画像をN x Nの領域に分割し(この領域をセルという)、セル内で3で求めたインデックスのヒストグラムを作成する。ただし、当表示は1でなく勾配角度を求める。 5. C x Cのセルを1つとして(これをブロックという)、ブロック内のセルのヒストグラムを次式で正規化する。これを1セルずつずらしながら行うので、一つのセルが何回も正規化される。 ここではpythonを用いてHOGの5を実装をしなさい。 C = 3 として、3 x 3のセルを1ブロックとして扱い、ヒストグラムの正規化を行え。 h(t) = h(t) / sqrt(Sum h(t) + epsilon) 通常は epsilon=1 これでHOG特徴量が得られた。
mport cv2 import numpy as np import matplotlib.pyplot as plt # get HOG def HOG(img): # Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Magnitude and gradient def get_gradXY(gray): H, W = gray.shape # padding before grad gray = np.pad(gray, (1, 1), 'edge') # get grad x gx = gray[1:H+1, 2:] - gray[1:H+1, :W] # get grad y gy = gray[2:, 1:W+1] - gray[:H, 1:W+1] # replace 0 with gx[gx == 0] = 1e-6 return gx, gy # get magnitude and gradient def get_MagGrad(gx, gy): # get gradient maginitude magnitude = np.sqrt(gx ** 2 + gy ** 2) # get gradient angle gradient = np.arctan(gy / gx) gradient[gradient < 0] = np.pi / 2 + gradient[gradient < 0] + np.pi / 2 return magnitude, gradient # Gradient histogram def quantization(gradient): # prepare quantization table gradient_quantized = np.zeros_like(gradient, dtype=np.int) # quantization base d = np.pi / 9 # quantization for i in range(9): gradient_quantized[np.where((gradient >= d * i) & (gradient <= d * (i + 1)))] = i return gradient_quantized # get gradient histogram def gradient_histogram(gradient_quantized, magnitude, N=8): # get shape H, W = magnitude.shape # get cell num cell_N_H = H // N cell_N_W = W // N histogram = np.zeros((cell_N_H, cell_N_W, 9), dtype=np.float32) # each pixel for y in range(cell_N_H): for x in range(cell_N_W): for j in range(N): for i in range(N): histogram[y, x, gradient_quantized[y * 4 + j, x * 4 + i]] += magnitude[y * 4 + j, x * 4 + i] return histogram # histogram normalization def normalization(histogram, C=3, epsilon=1): cell_N_H, cell_N_W, _ = histogram.shape ## each histogram for y in range(cell_N_H): for x in range(cell_N_W): #for i in range(9): histogram[y, x] /= np.sqrt(np.sum(histogram[max(y - 1, 0) : min(y + 2, cell_N_H), max(x - 1, 0) : min(x + 2, cell_N_W)] ** 2) + epsilon) return histogram # 1. BGR -> Gray gray = BGR2GRAY(img) # 1. Gray -> Gradient x and y gx, gy = get_gradXY(gray) # 2. get gradient magnitude and angle magnitude, gradient = get_MagGrad(gx, gy) # 3. Quantization gradient_quantized = quantization(gradient) # 4. Gradient histogram histogram = gradient_histogram(gradient_quantized, magnitude) # 5. Histogram normalization histogram = normalization(histogram) return histogram # draw HOG def draw_HOG(img, histogram): # Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray def draw(gray, histogram, N=8): # get shape H, W = gray.shape cell_N_H, cell_N_W, _ = histogram.shape ## Draw out = gray[1 : H + 1, 1 : W + 1].copy().astype(np.uint8) for y in range(cell_N_H): for x in range(cell_N_W): cx = x * N + N // 2 cy = y * N + N // 2 x1 = cx + N // 2 - 1 y1 = cy x2 = cx - N // 2 + 1 y2 = cy h = histogram[y, x] / np.sum(histogram[y, x]) h /= h.max() for c in range(9): #angle = (20 * c + 10 - 90) / 180. * np.pi # get angle angle = (20 * c + 10) / 180. * np.pi rx = int(np.sin(angle) * (x1 - cx) + np.cos(angle) * (y1 - cy) + cx) ry = int(np.cos(angle) * (x1 - cx) - np.cos(angle) * (y1 - cy) + cy) lx = int(np.sin(angle) * (x2 - cx) + np.cos(angle) * (y2 - cy) + cx) ly = int(np.cos(angle) * (x2 - cx) - np.cos(angle) * (y2 - cy) + cy) # color is HOG value c = int(255. * h[c]) # draw line cv2.line(out, (lx, ly), (rx, ry), (c, c, c), thickness=1) return out # get gray gray = BGR2GRAY(img) # draw HOG out = draw(gray, histogram) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # get HOG histogram = HOG(img) # draw HOG out = draw_HOG(img, histogram) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
268
MIT
gasyori_100_knocks
pythonを用いて、ここではHOG特徴量を描画せよ。 描画はimori.jpgをグレースケール化したものに重ねれば見やすい。 方法としては、セル内のインデックスごとに角度がついて直線を描けばよく、ヒストグラムの値が大きいほど白、値が小さいほど黒で描くと見やすい。
import cv2 import numpy as np import matplotlib.pyplot as plt # BGR -> HSV def BGR2HSV(_img): img = _img.copy() / 255. hsv = np.zeros_like(img, dtype=np.float32) # get max and min max_v = np.max(img, axis=2).copy() min_v = np.min(img, axis=2).copy() min_arg = np.argmin(img, axis=2) # H hsv[..., 0][np.where(max_v == min_v)]= 0 ## if min == B ind = np.where(min_arg == 0) hsv[..., 0][ind] = 60 * (img[..., 1][ind] - img[..., 2][ind]) / (max_v[ind] - min_v[ind]) + 60 ## if min == R ind = np.where(min_arg == 2) hsv[..., 0][ind] = 60 * (img[..., 0][ind] - img[..., 1][ind]) / (max_v[ind] - min_v[ind]) + 180 ## if min == G ind = np.where(min_arg == 1) hsv[..., 0][ind] = 60 * (img[..., 2][ind] - img[..., 0][ind]) / (max_v[ind] - min_v[ind]) + 300 # S hsv[..., 1] = max_v.copy() - min_v.copy() # V hsv[..., 2] = max_v.copy() return hsv # make mask def get_mask(hsv): mask = np.zeros_like(hsv[..., 0]) #mask[np.where((hsv > 180) & (hsv[0] < 260))] = 255 mask[np.logical_and((hsv[..., 0] > 180), (hsv[..., 0] < 260))] = 255 return mask # Read image img = cv2.imread("imori.jpg").astype(np.float32) # RGB > HSV hsv = BGR2HSV(img) # color tracking mask = get_mask(hsv) out = mask.astype(np.uint8) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
269
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgに対してHSVを用いて青色の箇所のみが255となる画像を作成せよ。 カラートラッキングとは特定の色の箇所を抽出する手法である。 ただし、RGBの状態で色成分を指定するのは256^3のパターンがあり、とても大変である(というか手動ではかなり難しい)ので、HSV変換を用いる。 HSV変換とは Q.5で用いた処理であるが、RGBをH(色相)、S(彩度)、V(明度)に変換する手法である。 - Saturation(彩度) 彩度が小さいほど白、彩度が大きいほど色が濃くなる。 0<=S<=1 - Value (明度) 明度が小さいほど黒くなり、明度が大きいほど色がきれいになる。 0<=V<=1 - Hue(色相) 色を0<=H<=360の角度で表し、具体的には次のように表される。 赤 黄色 緑 水色 青 紫 赤 0 60 120 180 240 300 360 つまり、青色のカラートラッキングを行うにはHSV変換を行い、180<=H<=260となる位置が255となるような二値画像を出力すればよい。
import cv2 import numpy as np import matplotlib.pyplot as plt # BGR -> HSV def BGR2HSV(_img): img = _img.copy() / 255. hsv = np.zeros_like(img, dtype=np.float32) # get max and min max_v = np.max(img, axis=2).copy() min_v = np.min(img, axis=2).copy() min_arg = np.argmin(img, axis=2) # H hsv[..., 0][np.where(max_v == min_v)]= 0 ## if min == B ind = np.where(min_arg == 0) hsv[..., 0][ind] = 60 * (img[..., 1][ind] - img[..., 2][ind]) / (max_v[ind] - min_v[ind]) + 60 ## if min == R ind = np.where(min_arg == 2) hsv[..., 0][ind] = 60 * (img[..., 0][ind] - img[..., 1][ind]) / (max_v[ind] - min_v[ind]) + 180 ## if min == G ind = np.where(min_arg == 1) hsv[..., 0][ind] = 60 * (img[..., 2][ind] - img[..., 0][ind]) / (max_v[ind] - min_v[ind]) + 300 # S hsv[..., 1] = max_v.copy() - min_v.copy() # V hsv[..., 2] = max_v.copy() return hsv # make mask def get_mask(hsv): mask = np.zeros_like(hsv[..., 0]) #mask[np.where((hsv > 180) & (hsv[0] < 260))] = 255 mask[np.logical_and((hsv[..., 0] > 180), (hsv[..., 0] < 260))] = 1 return mask # masking def masking(img, mask): mask = 1 - mask out = img.copy() # mask [h, w] -> [h, w, channel] mask = np.tile(mask, [3, 1, 1]).transpose([1, 2, 0]) out *= mask return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # RGB > HSV hsv = BGR2HSV(img / 255.) # color tracking mask = get_mask(hsv) # masking out = masking(img, mask) out = out.astype(np.uint8) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
270
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgに対してHSVを用いて青色の箇所のみが黒くなるようにマスキングせよ。 このように白黒のバイナリ画像を用いて黒部分に対応する元画像の画素を黒に変更する操作をマスキングという。 青色箇所の抽出はHSVで180<=H<=260となる位置が1となるような二値画像を作成し、それの0と1を反転したものと元画像との積をとればよい。 これによりある程度のイモリの部分の抽出ができる。
import cv2 import numpy as np import matplotlib.pyplot as plt # BGR -> HSV def BGR2HSV(_img): img = _img.copy() / 255. hsv = np.zeros_like(img, dtype=np.float32) # get max and min max_v = np.max(img, axis=2).copy() min_v = np.min(img, axis=2).copy() min_arg = np.argmin(img, axis=2) # H hsv[..., 0][np.where(max_v == min_v)]= 0 ## if min == B ind = np.where(min_arg == 0) hsv[..., 0][ind] = 60 * (img[..., 1][ind] - img[..., 2][ind]) / (max_v[ind] - min_v[ind]) + 60 ## if min == R ind = np.where(min_arg == 2) hsv[..., 0][ind] = 60 * (img[..., 0][ind] - img[..., 1][ind]) / (max_v[ind] - min_v[ind]) + 180 ## if min == G ind = np.where(min_arg == 1) hsv[..., 0][ind] = 60 * (img[..., 2][ind] - img[..., 0][ind]) / (max_v[ind] - min_v[ind]) + 300 # S hsv[..., 1] = max_v.copy() - min_v.copy() # V hsv[..., 2] = max_v.copy() return hsv # make mask def get_mask(hsv): mask = np.zeros_like(hsv[..., 0]) #mask[np.where((hsv > 180) & (hsv[0] < 260))] = 255 mask[np.logical_and((hsv[..., 0] > 180), (hsv[..., 0] < 260))] = 1 return mask # masking def masking(img, mask): mask = 1 - mask out = img.copy() # mask [h, w] -> [h, w, channel] mask = np.tile(mask, [3, 1, 1]).transpose([1, 2, 0]) out *= mask return out # Erosion def Erode(img, Erode_time=1): H, W = img.shape out = img.copy() # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each erode for i in range(Erode_time): tmp = np.pad(out, (1, 1), 'edge') # erode for y in range(1, H + 1): for x in range(1, W + 1): if np.sum(MF * tmp[y - 1 : y + 2 , x - 1 : x + 2]) < 1 * 4: out[y - 1, x - 1] = 0 return out # Dilation def Dilate(img, Dil_time=1): H, W = img.shape # kernel MF = np.array(((0, 1, 0), (1, 0, 1), (0, 1, 0)), dtype=np.int) # each dilate time out = img.copy() for i in range(Dil_time): tmp = np.pad(out, (1, 1), 'edge') for y in range(1, H + 1): for x in range(1, W + 1): if np.sum(MF * tmp[y - 1 : y + 2, x - 1 : x + 2]) >= 1: out[y - 1, x - 1] = 1 return out # Opening morphology def Morphology_Opening(img, time=1): out = Erode(img, Erode_time=time) out = Dilate(out, Dil_time=time) return out # Closing morphology def Morphology_Closing(img, time=1): out = Dilate(img, Dil_time=time) out = Erode(out, Erode_time=time) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # RGB > HSV hsv = BGR2HSV(img / 255.) # color tracking mask = get_mask(hsv) # closing mask = Morphology_Closing(mask, time=5) # opening mask = Morphology_Opening(mask, time=5) # masking out = masking(img, mask) out = out.astype(np.uint8) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
code_generation
271
MIT
gasyori_100_knocks
マスク処理が雑になってしまっていたので、画像の細かい部分が削除されていたり、背景がところどころ残ってしまった。 pythonを用いて、マスク画像にN=5のクロージング処理とオープニング処理を施してマスク画像を正確にして、マスキングを行え。
import cv2 import numpy as np import matplotlib.pyplot as plt # Grayscale def BGR2GRAY(img): # Grayscale gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Bi-Linear interpolation def bl_interpolate(img, ax=1., ay=1.): if len(img.shape) > 2: H, W, C = img.shape else: H, W = img.shape C = 1 aH = int(ay * H) aW = int(ax * W) # get position of resized image y = np.arange(aH).repeat(aW).reshape(aW, -1) x = np.tile(np.arange(aW), (aH, 1)) # get position of original position y = (y / ay) x = (x / ax) ix = np.floor(x).astype(np.int) iy = np.floor(y).astype(np.int) ix = np.minimum(ix, W-2) iy = np.minimum(iy, H-2) # get distance dx = x - ix dy = y - iy if C > 1: dx = np.repeat(np.expand_dims(dx, axis=-1), C, axis=-1) dy = np.repeat(np.expand_dims(dy, axis=-1), C, axis=-1) # interpolation out = (1-dx) * (1-dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix+1] + (1 - dx) * dy * img[iy+1, ix] + dx * dy * img[iy+1, ix+1] out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float) gray = BGR2GRAY(img) # Bilinear interpolation out = bl_interpolate(gray.astype(np.float32), ax=0.5, ay=0.5) # Bilinear interpolation out = bl_interpolate(out, ax=2., ay=2.) out = out.astype(np.uint8) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
272
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgをグレースケールにしたものを0.5倍に縮小した後に2倍に拡大した画像を求めよ。この処理を行うと、ぼやけた画像ができる。 拡大縮小にはbi-linear補間を用いよ。bi-linear補間をメソッド(関数)化すると、プログラムが簡潔にできる。
import cv2 import numpy as np import matplotlib.pyplot as plt # Grayscale def BGR2GRAY(img): # Grayscale gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Bi-Linear interpolation def bl_interpolate(img, ax=1., ay=1.): if len(img.shape) > 2: H, W, C = img.shape else: H, W = img.shape C = 1 aH = int(ay * H) aW = int(ax * W) # get position of resized image y = np.arange(aH).repeat(aW).reshape(aW, -1) x = np.tile(np.arange(aW), (aH, 1)) # get position of original position y = (y / ay) x = (x / ax) ix = np.floor(x).astype(np.int) iy = np.floor(y).astype(np.int) ix = np.minimum(ix, W-2) iy = np.minimum(iy, H-2) # get distance dx = x - ix dy = y - iy if C > 1: dx = np.repeat(np.expand_dims(dx, axis=-1), C, axis=-1) dy = np.repeat(np.expand_dims(dy, axis=-1), C, axis=-1) # interpolation out = (1-dx) * (1-dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix+1] + (1 - dx) * dy * img[iy+1, ix] + dx * dy * img[iy+1, ix+1] out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float) gray = BGR2GRAY(img) # Bilinear interpolation out = bl_interpolate(gray.astype(np.float32), ax=0.5, ay=0.5) # Bilinear interpolation out = bl_interpolate(out, ax=2., ay=2.) out = np.abs(out - gray) out = out / out.max() * 255 out = out.astype(np.uint8) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
273
MIT
gasyori_100_knocks
imori.jpgをグレースケールにしたものを0.5倍に縮小した後に2倍に拡大した画像を求めよ。 この処理を行うと、ぼやけた画像ができる。拡大縮小にはbi-linear補間を用いよ。 pythonを用いて、上記の処理で得た画像と元画像の差分を求め、[0,255]に正規化せよ。 ここで求めた画像はエッジとなっている。つまり、画像中の高周波成分をとったことになる。
import cv2 import numpy as np import matplotlib.pyplot as plt # Grayscale def BGR2GRAY(img): # Grayscale gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Bi-Linear interpolation def bl_interpolate(img, ax=1., ay=1.): if len(img.shape) > 2: H, W, C = img.shape else: H, W = img.shape C = 1 aH = int(ay * H) aW = int(ax * W) # get position of resized image y = np.arange(aH).repeat(aW).reshape(aW, -1) x = np.tile(np.arange(aW), (aH, 1)) # get position of original position y = (y / ay) x = (x / ax) ix = np.floor(x).astype(np.int) iy = np.floor(y).astype(np.int) ix = np.minimum(ix, W-2) iy = np.minimum(iy, H-2) # get distance dx = x - ix dy = y - iy if C > 1: dx = np.repeat(np.expand_dims(dx, axis=-1), C, axis=-1) dy = np.repeat(np.expand_dims(dy, axis=-1), C, axis=-1) # interpolation out = (1-dx) * (1-dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix+1] + (1 - dx) * dy * img[iy+1, ix] + dx * dy * img[iy+1, ix+1] out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # make image pyramid def make_pyramid(gray): # first element pyramid = [gray] # each scale for i in range(1, 6): # define scale a = 2. ** i # down scale p = bl_interpolate(gray, ax=1./a, ay=1. / a) # add pyramid list pyramid.append(p) return pyramid # Read image img = cv2.imread("imori.jpg").astype(np.float) gray = BGR2GRAY(img) # pyramid pyramid = make_pyramid(gray) for i in range(6): cv2.imwrite("out_{}.jpg".format(2**i), pyramid[i].astype(np.uint8)) plt.subplot(1, 6, i+1) plt.imshow(pyramid[i], cmap='gray') plt.axis('off') plt.xticks(color="None") plt.yticks(color="None") plt.show()
code_generation
274
MIT
gasyori_100_knocks
pythonを用いて、imori.pngを1/2, 1/4, 1/8, 1/16, 1/32にリサイズした画像を求めよ。 このように元画像を小さくリサイズして重ねたものをガウシアンピラミッドと呼ぶ。 このガウシアンピラミッドの概念は現在でも有効であり、画像をきれいにする超解像を行うディープラーニングの手法でもガウシアンピラミッドの概念が用いられる。
import cv2 import numpy as np import matplotlib.pyplot as plt # Grayscale def BGR2GRAY(img): # Grayscale gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Bi-Linear interpolation def bl_interpolate(img, ax=1., ay=1.): if len(img.shape) > 2: H, W, C = img.shape else: H, W = img.shape C = 1 aH = int(ay * H) aW = int(ax * W) # get position of resized image y = np.arange(aH).repeat(aW).reshape(aW, -1) x = np.tile(np.arange(aW), (aH, 1)) # get position of original position y = (y / ay) x = (x / ax) ix = np.floor(x).astype(np.int) iy = np.floor(y).astype(np.int) ix = np.minimum(ix, W-2) iy = np.minimum(iy, H-2) # get distance dx = x - ix dy = y - iy if C > 1: dx = np.repeat(np.expand_dims(dx, axis=-1), C, axis=-1) dy = np.repeat(np.expand_dims(dy, axis=-1), C, axis=-1) # interpolation out = (1-dx) * (1-dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix+1] + (1 - dx) * dy * img[iy+1, ix] + dx * dy * img[iy+1, ix+1] out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out # make image pyramid def make_pyramid(gray): # first element pyramid = [gray] # each scale for i in range(1, 6): # define scale a = 2. ** i # down scale p = bl_interpolate(gray, ax=1./a, ay=1. / a) # up scale p = bl_interpolate(p, ax=a, ay=a) # add pyramid list pyramid.append(p.astype(np.float32)) return pyramid # make saliency map def saliency_map(pyramid): # get shape H, W = pyramid[0].shape # prepare out image out = np.zeros((H, W), dtype=np.float32) # add each difference out += np.abs(pyramid[0] - pyramid[1]) out += np.abs(pyramid[0] - pyramid[3]) out += np.abs(pyramid[0] - pyramid[5]) out += np.abs(pyramid[1] - pyramid[4]) out += np.abs(pyramid[2] - pyramid[3]) out += np.abs(pyramid[3] - pyramid[5]) # normalization out = out / out.max() * 255 return out # Read image img = cv2.imread("imori.jpg").astype(np.float) # grayscale gray = BGR2GRAY(img) # pyramid pyramid = make_pyramid(gray) # pyramid -> saliency out = saliency_map(pyramid) out = out.astype(np.uint8) # Save result cv2.imshow("result", out) cv2.waitKey(0) cv2.imwrite("out.jpg", out)
code_generation
275
MIT
gasyori_100_knocks
pythonを用いて、ガウシアンピラミッドを用いた簡単な顕著性マップを作成しなさい。 顕著性マップとは画像の中で人間の目を引きやすい領域を表した画像である。 現在ではディープラーニングによる顕著性マップがよく用いられるが、本来は画像のRGB成分やHSV成分などのガウシアンピラミッドを作成し、それらの差分から求める手法がよく用いられた(例えばIttiらの手法などがある)。 ガウシアンピラミッドから簡単な顕著性マップを作成する。 アルゴリズムは、 1. ガウシアンピラミッドをそれぞれ、128, 64, 32, ...というサイズになっているが、はじめにそれらを128にリサイズせよ。リサイズはbi-linear補間を用いよ。 2. 作成したピラミッド(それぞれ0, 1, 2, 3, 4, 5と番号をふる)の2つを選び差分を求める。 3. 2で求めた差分を全て足し合わせ、[0, 255]に正規化せよ。 以上で顕著性マップが求められる。 2で選ぶ2つの画像は特に指定はしないが、いいものを選べば解答例のように顕著性マップが作成できる。 画像の細かい部分や色が周辺と極端に違う部分など、人の目に止まりやすい領域が白くなっているのが分かる。 解答例( (0,1), (0,3), (0,5), (1,4), (2,3), (3,5) を使用)
import cv2 import numpy as np import matplotlib.pyplot as plt # Gabor def Gabor_filter(K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0): # get half size d = K_size // 2 # prepare kernel gabor = np.zeros((K_size, K_size), dtype=np.float32) # each value for y in range(K_size): for x in range(K_size): # distance from center px = x - d py = y - d # degree -> radian theta = angle / 180. * np.pi # get kernel x _x = np.cos(theta) * px + np.sin(theta) * py # get kernel y _y = -np.sin(theta) * px + np.cos(theta) * py # fill kernel gabor[y, x] = np.exp(-(_x**2 + Gamma**2 * _y**2) / (2 * Sigma**2)) * np.cos(2*np.pi*_x/Lambda + Psi) # kernel normalization gabor /= np.sum(np.abs(gabor)) return gabor # get gabor kernel gabor = Gabor_filter(K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0) # Visualize # normalize to [0, 255] out = gabor - np.min(gabor) out /= np.max(out) out *= 255 out = out.astype(np.uint8) cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0)
code_generation
276
MIT
gasyori_100_knocks
pythonを用いて、ガボールフィルタを実装せよ。 ガボールフィルタとはガウス分布と周波数変換を合わせたフィルタであり、画像の特定方向のみのエッジを抽出する時に使われる。 フィルタは次式で定義される。 G(y, x) = exp(-(x'^2 + g^2 y'^2) / 2 s^2) * cos(2 pi x' / l + p) x' = cosA * x + sinA * y y' = -sinA * x + cosA * y y, x はフィルタの位置 フィルタサイズがKとすると、 y, x は [-K//2, k//2] の値を取る。 g ... gamma ガボールフィルタの楕円率 s ... sigma ガウス分布の標準偏差 l ... lambda 周波数の波長 p ... 位相オフセット A ... フィルタの回転 抽出したい角度を指定する。 ここでは、K=111, s=10, g = 1.2, l =10, p=0, A=0としてガボールフィルタを可視化せよ。 ガボールフィルタを実際に使う時は、フィルタ値の絶対値の和が1になるように正規化すると使いやすくなる。 答えでは可視化のためにフィルタの値を[0,255]に正規化している。
import cv2 import numpy as np import matplotlib.pyplot as plt # Gabor def Gabor_filter(K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0): # get half size d = K_size // 2 # prepare kernel gabor = np.zeros((K_size, K_size), dtype=np.float32) # each value for y in range(K_size): for x in range(K_size): # distance from center px = x - d py = y - d # degree -> radian theta = angle / 180. * np.pi # get kernel x _x = np.cos(theta) * px + np.sin(theta) * py # get kernel y _y = -np.sin(theta) * px + np.cos(theta) * py # fill kernel gabor[y, x] = np.exp(-(_x**2 + Gamma**2 * _y**2) / (2 * Sigma**2)) * np.cos(2*np.pi*_x/Lambda + Psi) # kernel normalization gabor /= np.sum(np.abs(gabor)) return gabor # define each angle As = [0, 45, 90, 135] # prepare pyplot plt.subplots_adjust(left=0, right=1, top=1, bottom=0, hspace=0, wspace=0.2) # each angle for i, A in enumerate(As): # get gabor kernel gabor = Gabor_filter(K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=A) # normalize to [0, 255] out = gabor - np.min(gabor) out /= np.max(out) out *= 255 out = out.astype(np.uint8) plt.subplot(1, 4, i+1) plt.imshow(out, cmap='gray') plt.axis('off') plt.title("Angle "+str(A)) plt.savefig("out.png") plt.show()
code_generation
277
MIT
gasyori_100_knocks
pythonを用いて、A=0, 45, 90, 135として回転方向のガボールフィルタを求めよ。 その他のパラメータは、K=111, s=10, g = 1.2, l =10, p=0とせよ。 ガボールフィルタとはガウス分布と周波数変換を合わせたフィルタであり、画像の特定方向のみのエッジを抽出する時に使われる。 フィルタは次式で定義される。 G(y, x) = exp(-(x'^2 + g^2 y'^2) / 2 s^2) * cos(2 pi x' / l + p) x' = cosA * x + sinA * y y' = -sinA * x + cosA * y y, x はフィルタの位置 フィルタサイズがKとすると、 y, x は [-K//2, k//2] の値を取る。 g ... gamma ガボールフィルタの楕円率 s ... sigma ガウス分布の標準偏差 l ... lambda 周波数の波長 p ... 位相オフセット A ... フィルタの回転 抽出したい角度を指定する。 ここではガボールフィルタをメソッド化すれば簡単に実装できる。
import cv2 import numpy as np import matplotlib.pyplot as plt # Grayscale def BGR2GRAY(img): # Grayscale gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Gabor def Gabor_filter(K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0): # get half size d = K_size // 2 # prepare kernel gabor = np.zeros((K_size, K_size), dtype=np.float32) # each value for y in range(K_size): for x in range(K_size): # distance from center px = x - d py = y - d # degree -> radian theta = angle / 180. * np.pi # get kernel x _x = np.cos(theta) * px + np.sin(theta) * py # get kernel y _y = -np.sin(theta) * px + np.cos(theta) * py # fill kernel gabor[y, x] = np.exp(-(_x**2 + Gamma**2 * _y**2) / (2 * Sigma**2)) * np.cos(2*np.pi*_x/Lambda + Psi) # kernel normalization gabor /= np.sum(np.abs(gabor)) return gabor def Gabor_filtering(gray, K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0): # get shape H, W = gray.shape # padding gray = np.pad(gray, (K_size//2, K_size//2), 'edge') # prepare out image out = np.zeros((H, W), dtype=np.float32) # get gabor filter gabor = Gabor_filter(K_size=K_size, Sigma=Sigma, Gamma=Gamma, Lambda=Lambda, Psi=0, angle=angle) # filtering for y in range(H): for x in range(W): out[y, x] = np.sum(gray[y : y + K_size, x : x + K_size] * gabor) out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out def Gabor_process(img): # gray scale gray = BGR2GRAY(img).astype(np.float32) # define angle As = [0, 45, 90, 135] # prepare pyplot plt.subplots_adjust(left=0, right=1, top=1, bottom=0, hspace=0, wspace=0.2) # each angle for i, A in enumerate(As): # gabor filtering out = Gabor_filtering(gray, K_size=11, Sigma=1.5, Gamma=1.2, Lambda=3, angle=A) plt.subplot(1, 4, i+1) plt.imshow(out, cmap='gray') plt.axis('off') plt.title("Angle "+str(A)) plt.savefig("out.png") plt.show() # Read image img = cv2.imread("imori.jpg").astype(np.float32) # gabor process Gabor_process(img)
code_generation
278
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgをグレースケール化し、A=0, 45, 90, 135 のガボールフィルタでフィルタリングせよ。 パラメータはK=11, s=1.5, g=1.2, l=3, p=0とする。 ガボールフィルタでは指定した方向のエッジを抽出することができ、ガボールフィルタはエッジの特徴抽出に優れている。 ガボールフィルタは生物の視神経における脳内の一次視覚野(V1)での働きに近いとされていて、つまり生物が見ている時の眼の前の画像の特徴抽出を再現しているともいわれる。 ディープラーニングのConvolutional層はガボールフィルタの働きに近いとも考えられている。しかし、ディープラーニングではフィルタの係数が機械学習によって自動的に決定される。機械学習の結果、ガボールフィルタに近い働きが生じると言われる。
import cv2 import numpy as np import matplotlib.pyplot as plt # Grayscale def BGR2GRAY(img): # Grayscale gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Gabor def Gabor_filter(K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0): # get half size d = K_size // 2 # prepare kernel gabor = np.zeros((K_size, K_size), dtype=np.float32) # each value for y in range(K_size): for x in range(K_size): # distance from center px = x - d py = y - d # degree -> radian theta = angle / 180. * np.pi # get kernel x _x = np.cos(theta) * px + np.sin(theta) * py # get kernel y _y = -np.sin(theta) * px + np.cos(theta) * py # fill kernel gabor[y, x] = np.exp(-(_x**2 + Gamma**2 * _y**2) / (2 * Sigma**2)) * np.cos(2*np.pi*_x/Lambda + Psi) # kernel normalization gabor /= np.sum(np.abs(gabor)) return gabor def Gabor_filtering(gray, K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0): # get shape H, W = gray.shape # padding gray = np.pad(gray, (K_size//2, K_size//2), 'edge') # prepare out image out = np.zeros((H, W), dtype=np.float32) # get gabor filter gabor = Gabor_filter(K_size=K_size, Sigma=Sigma, Gamma=Gamma, Lambda=Lambda, Psi=0, angle=angle) # filtering for y in range(H): for x in range(W): out[y, x] = np.sum(gray[y : y + K_size, x : x + K_size] * gabor) out = np.clip(out, 0, 255) out = out.astype(np.uint8) return out def Gabor_process(img): # get shape H, W, _ = img.shape # gray scale gray = BGR2GRAY(img).astype(np.float32) # define angle As = [0, 45, 90, 135] # prepare pyplot plt.subplots_adjust(left=0, right=1, top=1, bottom=0, hspace=0, wspace=0.2) out = np.zeros([H, W], dtype=np.float32) # each angle for i, A in enumerate(As): # gabor filtering _out = Gabor_filtering(gray, K_size=11, Sigma=1.5, Gamma=1.2, Lambda=3, angle=A) # add gabor filtered image out += _out # scale normalization out = out / out.max() * 255 out = out.astype(np.uint8) return out # Read image img = cv2.imread("imori.jpg").astype(np.float32) # gabor process out = Gabor_process(img) cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0)
code_generation
279
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgをグレースケール化し、A=0, 45, 90, 135 のガボールフィルタでフィルタリングした4枚の画像を足し合わせることで、画像の特徴を抽出せよ。 結果を見ると、画像の輪郭部分が白くなっていることからエッジ検出のような出力を得たように見える。 ディープラーニングのCNN(Convolutional Neural Network)では、最初に画像の特徴を抽出する働きが備わっているが、その特徴抽出の計算はこの問で行ったような操作を延々と繰り返している。ディープラーニングではこのようにして画像の特徴を自動的に抽出している。
import cv2 import numpy as np import matplotlib.pyplot as plt # Hessian corner detection def Hessian_corner(img): ## Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] gray = gray.astype(np.uint8) return gray ## Sobel def Sobel_filtering(gray): # get shape H, W = gray.shape # sobel kernel sobely = np.array(((1, 2, 1), (0, 0, 0), (-1, -2, -1)), dtype=np.float32) sobelx = np.array(((1, 0, -1), (2, 0, -2), (1, 0, -1)), dtype=np.float32) # padding tmp = np.pad(gray, (1, 1), 'edge') # prepare Ix = np.zeros_like(gray, dtype=np.float32) Iy = np.zeros_like(gray, dtype=np.float32) # get differential for y in range(H): for x in range(W): Ix[y, x] = np.mean(tmp[y : y + 3, x : x + 3] * sobelx) Iy[y, x] = np.mean(tmp[y : y + 3, x : x + 3] * sobely) Ix2 = Ix ** 2 Iy2 = Iy ** 2 Ixy = Ix * Iy return Ix2, Iy2, Ixy ## Hessian def corner_detect(gray, Ix2, Iy2, Ixy): # get shape H, W = gray.shape # prepare for show detection out = np.array((gray, gray, gray)) out = np.transpose(out, (1,2,0)) # get Hessian value Hes = np.zeros((H, W)) for y in range(H): for x in range(W): Hes[y,x] = Ix2[y,x] * Iy2[y,x] - Ixy[y,x] ** 2 ## Detect Corner and show for y in range(H): for x in range(W): if Hes[y,x] == np.max(Hes[max(y-1, 0) : min(y+2, H), max(x-1, 0) : min(x+2, W)]) and Hes[y, x] > np.max(Hes) * 0.1: out[y, x] = [0, 0, 255] out = out.astype(np.uint8) return out # 1. grayscale gray = BGR2GRAY(img) # 2. get difference image Ix2, Iy2, Ixy = Sobel_filtering(gray) # 3. corner detection out = corner_detect(gray, Ix2, Iy2, Ixy) return out # Read image img = cv2.imread("thorino.jpg").astype(np.float32) # Hessian corner detection out = Hessian_corner(img) cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0)
code_generation
280
MIT
gasyori_100_knocks
pythonを用いて、thorino.jpgにHessian(ヘシアン)のコーナー検出を行え。 コーナー検出とはエッジにおける角の点を検出することである。 コーナーは曲率が大きくなる点であり、次式のガウス曲率において、 ガウス曲率 K = det(H) / (1 + Ix^2 + Iy^2)^2 det(H) = Ixx Iyy - IxIy^2 H ... ヘシアン行列。画像の二次微分(グレースケール画像などに対して、Sobelフィルタを掛けて求められる)。画像上の一点に対して、次式で定義される。 Ix ... x方向のsobelフィルタを掛けたもの。 Iy ... y方向のsobelフィルタを掛けたもの。 H = [ Ix^2 IxIy] IxIy Iy^2 ヘシアンのコーナー検出では、det(H)が極大点をコーナーとみなす。 極大点は注目画素と8近傍を比較して、注目画素の値が最大であれば極大点として扱う。 解答ではdet(H)が極大点かつ、max(det(H))*0.1を超過する点をコーナーとしている。
import cv2 import numpy as np import matplotlib.pyplot as plt # Harris corner detection def Harris_corner_step1(img): ## Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] gray = gray.astype(np.uint8) return gray ## Sobel def Sobel_filtering(gray): # get shape H, W = gray.shape # sobel kernel sobely = np.array(((1, 2, 1), (0, 0, 0), (-1, -2, -1)), dtype=np.float32) sobelx = np.array(((1, 0, -1), (2, 0, -2), (1, 0, -1)), dtype=np.float32) # padding tmp = np.pad(gray, (1, 1), 'edge') # prepare Ix = np.zeros_like(gray, dtype=np.float32) Iy = np.zeros_like(gray, dtype=np.float32) # get differential for y in range(H): for x in range(W): Ix[y, x] = np.mean(tmp[y : y + 3, x : x + 3] * sobelx) Iy[y, x] = np.mean(tmp[y : y + 3, x : x + 3] * sobely) Ix2 = Ix ** 2 Iy2 = Iy ** 2 Ixy = Ix * Iy return Ix2, Iy2, Ixy # gaussian filtering def gaussian_filtering(I, K_size=3, sigma=3): # get shape H, W = I.shape ## gaussian I_t = np.pad(I, (K_size // 2, K_size // 2), 'edge') # gaussian kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(K_size): for y in range(K_size): _x = x - K_size // 2 _y = y - K_size // 2 K[y, x] = np.exp( -(_x ** 2 + _y ** 2) / (2 * (sigma ** 2))) K /= (sigma * np.sqrt(2 * np.pi)) K /= K.sum() # filtering for y in range(H): for x in range(W): I[y,x] = np.sum(I_t[y : y + K_size, x : x + K_size] * K) return I # 1. grayscale gray = BGR2GRAY(img) # 2. get difference image Ix2, Iy2, Ixy = Sobel_filtering(gray) # 3. gaussian filtering Ix2 = gaussian_filtering(Ix2, K_size=3, sigma=3) Iy2 = gaussian_filtering(Iy2, K_size=3, sigma=3) Ixy = gaussian_filtering(Ixy, K_size=3, sigma=3) # show result plt.subplots_adjust(left=0, right=1, top=1, bottom=0, hspace=0, wspace=0.2) plt.subplot(1,3,1) plt.imshow(Ix2, cmap='gray') plt.title("Ix^2") plt.axis("off") plt.subplot(1,3,2) plt.imshow(Iy2, cmap='gray') plt.title("Iy^2") plt.axis("off") plt.subplot(1,3,3) plt.imshow(Ixy, cmap='gray') plt.title("Ixy") plt.axis("off") plt.savefig("out.png") plt.show() # Read image img = cv2.imread("thorino.jpg").astype(np.float32) # Harris corner detection step1 out = Harris_corner_step1(img)
code_generation
281
MIT
gasyori_100_knocks
Harrisのコーナー検出のアルゴリズムは、 1. 画像をグレースケール化。 2. Sobelフィルタにより、ヘシアン行列を求める。 H = [ Ix^2 IxIy] IxIy Iy^2 3. Ix^2, Iy^2, IxIyにそれぞれガウシアンフィルターをかける。 4. 各ピクセル毎に、R = det(H) - k (trace(H))^2 を計算する。 (kは実験的に0.04 - 0.16らへんが良いとされる) 5. R >= max(R) * th を満たすピクセルがコーナーとなる。 (thは0.1となることが多い) 各パラメータは以下の通り。 - ガウシアンフィルター(k=3, sigma=3) - k = 0.04, th = 0.1 pythonを用いて、処理1-3までを実装せよ。
import cv2 import numpy as np import matplotlib.pyplot as plt # Harris corner detection def Harris_corner(img): ## Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] gray = gray.astype(np.uint8) return gray ## Sobel def Sobel_filtering(gray): # get shape H, W = gray.shape # sobel kernel sobely = np.array(((1, 2, 1), (0, 0, 0), (-1, -2, -1)), dtype=np.float32) sobelx = np.array(((1, 0, -1), (2, 0, -2), (1, 0, -1)), dtype=np.float32) # padding tmp = np.pad(gray, (1, 1), 'edge') # prepare Ix = np.zeros_like(gray, dtype=np.float32) Iy = np.zeros_like(gray, dtype=np.float32) # get differential for y in range(H): for x in range(W): Ix[y, x] = np.mean(tmp[y : y + 3, x : x + 3] * sobelx) Iy[y, x] = np.mean(tmp[y : y + 3, x : x + 3] * sobely) Ix2 = Ix ** 2 Iy2 = Iy ** 2 Ixy = Ix * Iy return Ix2, Iy2, Ixy # gaussian filtering def gaussian_filtering(I, K_size=3, sigma=3): # get shape H, W = I.shape ## gaussian I_t = np.pad(I, (K_size // 2, K_size // 2), 'edge') # gaussian kernel K = np.zeros((K_size, K_size), dtype=np.float) for x in range(K_size): for y in range(K_size): _x = x - K_size // 2 _y = y - K_size // 2 K[y, x] = np.exp( -(_x ** 2 + _y ** 2) / (2 * (sigma ** 2))) K /= (sigma * np.sqrt(2 * np.pi)) K /= K.sum() # filtering for y in range(H): for x in range(W): I[y,x] = np.sum(I_t[y : y + K_size, x : x + K_size] * K) return I # corner detect def corner_detect(gray, Ix2, Iy2, Ixy, k=0.04, th=0.1): # prepare output image out = np.array((gray, gray, gray)) out = np.transpose(out, (1,2,0)) # get R R = (Ix2 * Iy2 - Ixy ** 2) - k * ((Ix2 + Iy2) ** 2) # detect corner out[R >= np.max(R) * th] = [0, 0, 255] out = out.astype(np.uint8) return out # 1. grayscale gray = BGR2GRAY(img) # 2. get difference image Ix2, Iy2, Ixy = Sobel_filtering(gray) # 3. gaussian filtering Ix2 = gaussian_filtering(Ix2, K_size=3, sigma=3) Iy2 = gaussian_filtering(Iy2, K_size=3, sigma=3) Ixy = gaussian_filtering(Ixy, K_size=3, sigma=3) # 4. corner detect out = corner_detect(gray, Ix2, Iy2, Ixy) return out # Read image img = cv2.imread("thorino.jpg").astype(np.float32) # Harris corner detection out = Harris_corner(img) cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0)
code_generation
282
MIT
gasyori_100_knocks
Harrisのコーナー検出のアルゴリズムは、 1. 画像をグレースケール化。 2. Sobelフィルタにより、ヘシアン行列を求める。 H = [ Ix^2 IxIy] IxIy Iy^2 3. Ix^2, Iy^2, IxIyにそれぞれガウシアンフィルターをかける。 4. 各ピクセル毎に、R = det(H) - k (trace(H))^2 を計算する。 (kは実験的に0.04 - 0.16らへんが良いとされる) 5. R >= max(R) * th を満たすピクセルがコーナーとなる。 (thは0.1となることが多い) 各パラメータは以下の通り。 - ガウシアンフィルター(k=3, sigma=3) - k = 0.04, th = 0.1 pythonを用いて、処理4-5を実装せよ。
mport cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob ## Dicrease color def dic_color(img): img //= 63 img = img * 64 + 32 return img ## Database def get_DB(): # get image paths train = glob("dataset/train_*") train.sort() # prepare database db = np.zeros((len(train), 13), dtype=np.int32) # each image for i, path in enumerate(train): img = dic_color(cv2.imread(path)) # get histogram for j in range(4): db[i, j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) db[i, j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) db[i, j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get class if 'akahara' in path: cls = 0 elif 'madara' in path: cls = 1 # store class label db[i, -1] = cls img_h = img.copy() // 64 img_h[..., 1] += 4 img_h[..., 2] += 8 plt.subplot(2, 5, i+1) plt.hist(img_h.ravel(), bins=12, rwidth=0.8) plt.title(path) print(db) plt.show() # get database get_DB()
code_generation
283
MIT
gasyori_100_knocks
pythonを用いて、簡単な画像認識を作成しなさい。 画像認識とは画像に写っているモノが何か(どのクラスに属するか)を特定するタスクである。画像認識はよく、画像分類、Classification(クラス分類)、Categorization(カテゴライゼーション)、Clustering(クラスタリング)、などと呼ばれる。 よくある手法は画像から何らかの特徴(HOGやSIFT, SURFなど)を抽出し、その特徴によりクラスを判別する。CNNが流行る以前はこのアプローチがよく取られたが、CNNは特徴抽出から判別までを一括して行える。 ここでは、画像の色ヒストグラムを用いた簡単な画像認識を行う。 アルゴリズムとしては、 1. 画像(train_*.jpg)を減色処理(Q.6. RGBをそれぞれ4階調)する。 2. 減色処理した画像のヒストグラムを作成する。ここでのヒストグラムはRGBがそれぞれ4値をとるが、それらを区別するため、B=[1,4], G=[5,8], R=[9,12]のbin=12となる。それぞれの画像に対応するヒストグラムも保存する必要があるので注意。  つまり、database = np.zeros((10(学習データ数), 13(RGB + class), dtype=np.int) に学習データのヒストグラムを格納する必要がある。 3. 2のヒストグラムをデータベースとする。 4. 認識したい画像(test_@@@.jpg)とヒストグラムの差を計算して、特徴量とする。 5. ヒストグラムの差の合計で、最小となった画像が予測となるクラスである。つまり、色が近い画像と同じクラスになると考えられる。 ここではpythonを用いて処理1-3を実装し、ヒストグラムを可視化せよ。 学習データはdatasetフォルダにあり train_akahara_@@@.jpg (クラス1)と train_madara_@@@.jpg(クラス2) を用いる。(計10枚) akaharaとはアカハライモリ、madaraはマダライモリである。 このような予め特徴量を保存しておくデータベース型は人工知能第一世代の手法である。ようは、全部のパターンを暗記しておけばOKという考え方である。ただし、そうするとメモリを大量に消費するので使用が限られる手法である。
import cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob # Dicrease color def dic_color(img): img //= 63 img = img * 64 + 32 return img # Database def get_DB(): # get training image path train = glob("dataset/train_*") train.sort() # prepare database db = np.zeros((len(train), 13), dtype=np.int32) # prepare path database pdb = [] # each image for i, path in enumerate(train): # read image img = dic_color(cv2.imread(path)) #get histogram for j in range(4): db[i, j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) db[i, j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) db[i, j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get class if 'akahara' in path: cls = 0 elif 'madara' in path: cls = 1 # store class label db[i, -1] = cls # store image path pdb.append(path) return db, pdb # test def test_DB(db, pdb): # get test image path test = glob("dataset/test_*") test.sort() success_num = 0. # each image for path in test: # read image img = dic_color(cv2.imread(path)) # get histogram hist = np.zeros(12, dtype=np.int32) for j in range(4): hist[j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) hist[j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) hist[j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get histogram difference difs = np.abs(db[:, :12] - hist) difs = np.sum(difs, axis=1) # get argmin of difference pred_i = np.argmin(difs) # get prediction label pred = db[pred_i, -1] if pred == 0: pl = "akahara" elif pred == 1: pl = "madara" print(path, "is similar >>", pdb[pred_i], " Pred >>", pl) db, pdb = get_DB() test_DB(db, pdb)
code_generation
284
MIT
gasyori_100_knocks
pythonを用いて、簡単な画像認識を作成しなさい。 画像認識とは画像に写っているモノが何か(どのクラスに属するか)を特定するタスクである。画像認識はよく、画像分類、Classification(クラス分類)、Categorization(カテゴライゼーション)、Clustering(クラスタリング)、などと呼ばれる。 よくある手法は画像から何らかの特徴(HOGやSIFT, SURFなど)を抽出し、その特徴によりクラスを判別する。CNNが流行る以前はこのアプローチがよく取られたが、CNNは特徴抽出から判別までを一括して行える。 ここでは、画像の色ヒストグラムを用いた簡単な画像認識を行う。 アルゴリズムとしては、 1. 画像(train_*.jpg)を減色処理(Q.6. RGBをそれぞれ4階調)する。 2. 減色処理した画像のヒストグラムを作成する。ここでのヒストグラムはRGBがそれぞれ4値をとるが、それらを区別するため、B=[1,4], G=[5,8], R=[9,12]のbin=12となる。それぞれの画像に対応するヒストグラムも保存する必要があるので注意。  つまり、database = np.zeros((10(学習データ数), 13(RGB + class), dtype=np.int) に学習データのヒストグラムを格納する必要がある。 3. 2のヒストグラムをデータベースとする。 4. 認識したい画像(test_@@@.jpg)とヒストグラムの差を計算して、特徴量とする。 5. ヒストグラムの差の合計で、最小となった画像が予測となるクラスである。つまり、色が近い画像と同じクラスになると考えられる。 pythonを用いて処理4-5を実装せよ。 テストデータには test_akahara_@@@.jpgとtest_madara_@@@.jpgを用いよ。(計4枚) ただし、各画像と最もヒストグラム差分が小さい画像の名前と予測クラスの2つを出力せよ。 これはNearesetNeighbourと呼ばれる評価方法である。
import cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob # Dicrease color def dic_color(img): img //= 63 img = img * 64 + 32 return img # Database def get_DB(): # get training image path train = glob("dataset/train_*") train.sort() # prepare database db = np.zeros((len(train), 13), dtype=np.int32) # prepare path database pdb = [] # each image for i, path in enumerate(train): # read image img = dic_color(cv2.imread(path)) #get histogram for j in range(4): db[i, j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) db[i, j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) db[i, j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get class if 'akahara' in path: cls = 0 elif 'madara' in path: cls = 1 # store class label db[i, -1] = cls # store image path pdb.append(path) return db, pdb # test def test_DB(db, pdb): # get test image path test = glob("dataset/test_*") test.sort() accurate_N = 0. # each image for path in test: # read image img = dic_color(cv2.imread(path)) # get histogram hist = np.zeros(12, dtype=np.int32) for j in range(4): hist[j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) hist[j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) hist[j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get histogram difference difs = np.abs(db[:, :12] - hist) difs = np.sum(difs, axis=1) # get argmin of difference pred_i = np.argmin(difs) # get prediction label pred = db[pred_i, -1] if pred == 0: pred_label = "akahara" elif pred == 1: pred_label = "madara" gt = "akahara" if "akahara" in path else "madara" if gt == pred_label: accurate_N += 1 print(path, "is similar >>", pdb[pred_i], " Pred >>", pred_label) accuracy = accurate_N / len(test) print("Accuracy >>", accuracy, "({}/{})".format(int(accurate_N), len(test))) db, pdb = get_DB() test_DB(db, pdb)
code_generation
285
MIT
gasyori_100_knocks
pythonを用いて、画像認識の結果を評価しなさい。 画像認識の場合はどれくらい正解クラスを予想できたかを示すAccuracy(Precisionといったりもする)が一般的な評価指標である。Accuracyは次式で計算される。要はテストにおける得点率である。小数表示するときや、100掛けてパーセンテージで表すこともある。 Accuracy = (正解した画像数) / (テストした画像の総数) 以上を踏まえて、画像認識のAccuracyを求めよ。 なお、画像認識のアルゴリズムは以下の通りである。 画像認識アルゴリズムとしては、 1. 画像(train_*.jpg)を減色処理(Q.6. RGBをそれぞれ4階調)する。 2. 減色処理した画像のヒストグラムを作成する。ここでのヒストグラムはRGBがそれぞれ4値をとるが、それらを区別するため、B=[1,4], G=[5,8], R=[9,12]のbin=12となる。それぞれの画像に対応するヒストグラムも保存する必要があるので注意。  つまり、database = np.zeros((10(学習データ数), 13(RGB + class), dtype=np.int) に学習データのヒストグラムを格納する必要がある。 3. 2のヒストグラムをデータベースとする。 4. 認識したい画像(test_@@@.jpg)とヒストグラムの差を計算して、特徴量とする。 5. ヒストグラムの差の合計で、最小となった画像が予測となるクラスである。つまり、色が近い画像と同じクラスになると考えられる。
mport cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob # Dicrease color def dic_color(img): img //= 63 img = img * 64 + 32 return img # Database def get_DB(): # get training image path train = glob("dataset/train_*") train.sort() # prepare database db = np.zeros((len(train), 13), dtype=np.int32) pdb = [] # each train for i, path in enumerate(train): # read image img = dic_color(cv2.imread(path)) # histogram for j in range(4): db[i, j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) db[i, j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) db[i, j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get class if 'akahara' in path: cls = 0 elif 'madara' in path: cls = 1 # store class label db[i, -1] = cls # add image path pdb.append(path) return db, pdb # test def test_DB(db, pdb, N=3): # get test image path test = glob("dataset/test_*") test.sort() accuracy_N = 0. # each image for path in test: # read image img = dic_color(cv2.imread(path)) # get histogram hist = np.zeros(12, dtype=np.int32) for j in range(4): hist[j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) hist[j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) hist[j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get histogram difference difs = np.abs(db[:, :12] - hist) difs = np.sum(difs, axis=1) # get top N pred_i = np.argsort(difs)[:N] # predict class index pred = db[pred_i, -1] # get class label if len(pred[pred == 0]) > len(pred[pred == 1]): pl = "akahara" else: pl = 'madara' print(path, "is similar >> ", end='') for i in pred_i: print(pdb[i], end=', ') print("|Pred >>", pl) # count accuracy gt = "akahara" if "akahara" in path else "madara" if gt == pl: accuracy_N += 1. accuracy = accuracy_N / len(test) print("Accuracy >>", accuracy, "({}/{})".format(int(accuracy_N), len(test))) db, pdb = get_DB() test_DB(db, pdb)
code_generation
286
MIT
gasyori_100_knocks
ある画像認識タスクでは、test_madara_2.jpgがtrain_akahara_2.jpgと最も色が近い画像と判断された。 |test_marada_2.jpg|train_akahara_2.jpg| |:---:|:---:| |![](dataset/test_madara_2.jpg)|![](dataset/train_akahara_2.jpg)| 2つの画像を見比べるとたしかに両方とも緑の割合と黒の割合が近く見えるので、画像全体に対しての画像の色味が同じ様に見えてしまう。これは認識時のサンプルを一つにしたことによって、例外的な画像が選ばれてしまったためである。このように学習データの特徴は常にきれいに分離されているわけではなく、時に特徴の分布から逸しているサンプルも含まれる。 これを回避するために、ここではpythonを用いて色合いが近い画像認識したい画像(test_@@@.jpg)を3つ選び、それらの多数決によって予測クラスを決定し、Accuracyを計算せよ。 このように特徴が近いものを学習データからk個選んで判断する手法をk近傍(k-NN: k-Nearest Neighbor)という。NN法はk=1の場合とみれる。
import cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob # Dicrease color def dic_color(img): img //= 63 img = img * 64 + 32 return img # Database def get_DB(): # get training image path train = glob("dataset/test_*") train.sort() # prepare database db = np.zeros((len(train), 13), dtype=np.int32) pdb = [] # each train for i, path in enumerate(train): # read image img = dic_color(cv2.imread(path)) # histogram for j in range(4): db[i, j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) db[i, j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) db[i, j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get class if 'akahara' in path: cls = 0 elif 'madara' in path: cls = 1 # store class label db[i, -1] = cls # add image path pdb.append(path) return db, pdb # k-Means step1 def k_means_step1(db, pdb, Class=2): # copy database feats = db.copy() # initiate random seed np.random.seed(1) # assign random class for i in range(len(feats)): if np.random.random() < 0.5: feats[i, -1] = 0 else: feats[i, -1] = 1 # prepare gravity gs = np.zeros((Class, 12), dtype=np.float32) # get gravity for i in range(Class): gs[i] = np.mean(feats[np.where(feats[..., -1] == i)[0], :12], axis=0) print("assigned label") print(feats) print("Grabity") print(gs) db, pdb = get_DB() k_means_step1(db, pdb)
code_generation
287
MIT
gasyori_100_knocks
画像認識は教師データを必要とするいわゆる教師あり学習(supervised-training)のものすごく簡単なものだったが、ここでは教師を必要としない教師なし学習(unsupervised-training)で画像を分類する。 最も簡単な方法がK-meansクラスタリング法である。 これは予めクラス数が分かっている場合に使うことができ、特徴量を重心に分けながらクラスタリングする手法である。 K-Meansアルゴリズムとしては、 1. データにそれぞれランダムにクラスを割り当てる。 2. クラスごとに重心を計算する。 3. 各データと重心の距離を計算し、最も距離が近い重心のクラスを割り当てる。 4. 2-3をクラス変更がなくなるまで繰り返す。 ここでは、減色化とヒストグラムを特徴量として次のようにアルゴリズムを作成する。 1. 画像を減色化し、ヒストグラムを作成し、これを特徴量とする。 2. 各画像にランダムに0か1のクラスを割り当てる。 (ここでは、クラス数=2, np.random.seed(1) として、np.random.random() < thなら0、>= thなら1を割り当てる。th=0.5) 3. クラスが0、1の特徴量の重心(mean)をそれぞれ取る。(重心は gs = np.zeros((Class, 12), dtype=np.float32)に格納する。) 4. 各画像に対して、特徴量と重心の距離(ユークリッド距離(L1ノルム): 差を二乗し、その合計のsqrtをとったもの)を計算し、距離が近い重心のクラスを割り当てる。 5. 3-4をクラスの変更がなくなるまで繰り返す。 ここでは、pythonを用いて処理1-3までを実装せよ(4,5のことを考えてループを作らなくてもよい)。分類する画像は*test_@@@.jpg*とする。
import cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob # Dicrease color def dic_color(img): img //= 63 img = img * 64 + 32 return img # Database def get_DB(): # get training image path train = glob("dataset/test_*") train.sort() # prepare database db = np.zeros((len(train), 13), dtype=np.int32) pdb = [] # each train for i, path in enumerate(train): # read image img = dic_color(cv2.imread(path)) # histogram for j in range(4): db[i, j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) db[i, j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) db[i, j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get class if 'akahara' in path: cls = 0 elif 'madara' in path: cls = 1 # store class label db[i, -1] = cls # add image path pdb.append(path) return db, pdb # k-Means step2 def k_means_step2(db, pdb, Class=2): # copy database feats = db.copy() # initiate random seed np.random.seed(1) # assign random class for i in range(len(feats)): if np.random.random() < 0.5: feats[i, -1] = 0 else: feats[i, -1] = 1 while True: # prepare greavity gs = np.zeros((Class, 12), dtype=np.float32) change_count = 0 # compute gravity for i in range(Class): gs[i] = np.mean(feats[np.where(feats[..., -1] == i)[0], :12], axis=0) # re-labeling for i in range(len(feats)): # get distance each nearest graviry dis = np.sqrt(np.sum(np.square(np.abs(gs - feats[i, :12])), axis=1)) # get new label pred = np.argmin(dis, axis=0) # if label is difference from old label if int(feats[i, -1]) != pred: change_count += 1 feats[i, -1] = pred if change_count < 1: break for i in range(db.shape[0]): print(pdb[i], " Pred:", feats[i, -1]) db, pdb = get_DB() k_means_step2(db, pdb)
code_generation
288
MIT
gasyori_100_knocks
K-Meansアルゴリズムでは、 1. データにそれぞれランダムにクラスを割り当てる。 2. クラスごとに重心を計算する。 3. 各データと重心の距離を計算し、最も距離が近い重心のクラスを割り当てる。 4. 2-3をクラス変更がなくなるまで繰り返す。 ここでは、減色化とヒストグラムを特徴量として次のようにアルゴリズムを作成する。 1. 画像を減色化し、ヒストグラムを作成し、これを特徴量とする。 2. 各画像にランダムに0か1のクラスを割り当てる。 (ここでは、クラス数=2, np.random.seed(1) として、np.random.random() < thなら0、>= thなら1を割り当てる。th=0.5) 3. クラスが0、1の特徴量の重心(mean)をそれぞれ取る。(重心は gs = np.zeros((Class, 12), dtype=np.float32)に格納する。) 4. 各画像に対して、特徴量と重心の距離(ユークリッド距離(L1ノルム): 差を二乗し、その合計のsqrtをとったもの)を計算し、距離が近い重心のクラスを割り当てる。 5. 3-4をクラスの変更がなくなるまで繰り返す。 ここではpythonを用いて処理4-5も実装して、クラスタリングを行え。 ここで予測クラスが0,1となっているが、Q.85-87と違いラベルの順番はバラバラである。 なので、K-meansはあくまでカテゴリ別に分類する手法であり、それが具体的に何のクラスかまでは分からない。 また、クラス数は予めこちらが知って置かなければいけない。 K-meansクラスタリングでは最初に割り当てるラベルの状態によって、最後の出力が大きく左右されるので注意が必要である。 また、データ数が少ないと失敗しやすい。これはデータ数が少ないことで、真のデータの分布をサンプリングしにくいことが原因である。つまり、データ数が多いほどデータの分布が精度良くえられることによる。
import cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob # Dicrease color def dic_color(img): img //= 63 img = img * 64 + 32 return img # Database def get_DB(): # get training image path train = glob("dataset/train_*") train.sort() # prepare database db = np.zeros((len(train), 13), dtype=np.int32) pdb = [] # each train for i, path in enumerate(train): # read image img = dic_color(cv2.imread(path)) # histogram for j in range(4): db[i, j] = len(np.where(img[..., 0] == (64 * j + 32))[0]) db[i, j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0]) db[i, j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0]) # get class if 'akahara' in path: cls = 0 elif 'madara' in path: cls = 1 # store class label db[i, -1] = cls # add image path pdb.append(path) return db, pdb # k-Means def k_means(db, pdb, Class=2, th=0.5): # copy database feats = db.copy() # initiate random seed np.random.seed(4) # assign random class for i in range(len(feats)): if np.random.random() < th: feats[i, -1] = 0 else: feats[i, -1] = 1 while True: # prepare greavity gs = np.zeros((Class, 12), dtype=np.float32) change_count = 0 # compute gravity for i in range(Class): gs[i] = np.mean(feats[np.where(feats[..., -1] == i)[0], :12], axis=0) # re-labeling for i in range(len(feats)): # get distance each nearest graviry dis = np.sqrt(np.sum(np.square(np.abs(gs - feats[i, :12])), axis=1)) # get new label pred = np.argmin(dis, axis=0) # if label is difference from old label if int(feats[i, -1]) != pred: change_count += 1 feats[i, -1] = pred if change_count < 1: break for i in range(db.shape[0]): print(pdb[i], " Pred:", feats[i, -1]) db, pdb = get_DB() k_means(db, pdb, th=0.3)
code_generation
289
MIT
gasyori_100_knocks
pythonで、K-meansを用いて*train_@@@.jpg*の10枚を完璧にクラスタリングせよ。 ここでは、np.random.seed()の値やラベルを割り当てる閾値 np.random.random() < th のthを変更して、K-meansでクラスを完璧に予測せよ。 train_@@@.jpgはQ.89より画像数が2倍以上になっているので、クラスタリングしやすくなっている。 これは試行錯誤するしかない。
import cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob # K-means step1 def k_means_step1(img, Class=5): # get shape H, W, C = img.shape # initiate random seed np.random.seed(0) # reshape img = np.reshape(img, (H * W, -1)) # select one index randomly i = np.random.choice(np.arange(H * W), Class, replace=False) Cs = img[i].copy() print(Cs) clss = np.zeros((H * W), dtype=int) # each pixel for i in range(H * W): # get distance from base pixel dis = np.sqrt(np.sum((Cs - img[i]) ** 2, axis=1)) # get argmin distance clss[i] = np.argmin(dis) # show out = np.reshape(clss, (H, W)) * 50 out = out.astype(np.uint8) return out # read image img = cv2.imread("imori.jpg").astype(np.float32) # K-means step2 out = k_means_step1(img) cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0)
code_generation
290
MIT
gasyori_100_knocks
pythonを用いて、imori.jpgをK-meansを用いた減色処理せよ。 減色処理はQ.6でも扱ったが、Q.6では予め決めた色に減色した。ここで扱うのはK-meansを用いて動的に減色する色を決定する。 アルゴリズムは, 1. 画像からランダムにK個のRGB成分をサンプリングする。(これをクラスと呼ぶことにする。) 2. 画像のそれぞれの画素に対して色の距離が最小となるクラスのインデックスを割り振る。 色の距離 dis = sqrt( (R-R')^2 + (G-G')^2 + (B-B')^2) 3. 各インデックスに対応する色成分の平均をRGBそれぞれに対して取り、新たなクラスとする。 4. 元のクラスと新しいクラスが全く同じならK-meansを終了する。そうでなければ、新しいクラスを元クラスとして2-3を繰り返す。 5. 元画像の各画素で色の距離が最小となるクラスのRGBを割り当てる。 ここでは1-2を実装せよ。 - クラス数はk=5とする - ここでは画像をreshape((HxW, 3))にreshapeすると扱いやすくなる。 - 1においてはnp.random.seed(0)として、np.random.choice(np.arrange(画像のWxH), 5, replace=False) - まずは3-5のループを考えずに実装せよ # 最初に選べれた色 [[140. 121. 148.] [135. 109. 122.] [211. 189. 213.] [135. 86. 84.] [118. 99. 96.]] 最初に選ばれた色との色の距離でクラスのインデックスをつけたもの(アルゴリズム2)。 解答では0-4にインデックスの値をx50にして見やすいようにしている。
import cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob def k_means(img, Class=5): # get shape H, W, C = img.shape # initiate random seed np.random.seed(0) # reshape image img = np.reshape(img, (H * W, -1)) # get index randomly i = np.random.choice(np.arange(H * W), Class, replace=False) Cs = img[i].copy() while True: # prepare pixel class label clss = np.zeros((H * W), dtype=int) # each pixel for i in range(H * W): # get distance from index pixel dis = np.sqrt(np.sum((Cs - img[i])**2, axis=1)) # get argmin distance clss[i] = np.argmin(dis) # selected pixel values Cs_tmp = np.zeros((Class, 3)) # each class label for i in range(Class): Cs_tmp[i] = np.mean(img[clss == i], axis=0) # if not any change if (Cs == Cs_tmp).all(): break else: Cs = Cs_tmp.copy() # prepare out image out = np.zeros((H * W, 3), dtype=np.float32) # assign selected pixel values for i in range(Class): out[clss == i] = Cs[i] print(Cs) out = np.clip(out, 0, 255) # reshape out image out = np.reshape(out, (H, W, 3)) out = out.astype(np.uint8) return out # read image img = cv2.imread("imori.jpg").astype(np.float32) # K-means out = k_means(img) cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0)
code_generation
291
MIT
gasyori_100_knocks
減色処理のアルゴリズムは, 1. 画像からランダムにK個のRGB成分をサンプリングする。(これをクラスと呼ぶことにする。) 2. 画像のそれぞれの画素に対して色の距離が最小となるクラスのインデックスを割り振る。 色の距離 dis = sqrt( (R-R')^2 + (G-G')^2 + (B-B')^2) 3. 各インデックスに対応する色成分の平均をRGBそれぞれに対して取り、新たなクラスとする。 4. 元のクラスと新しいクラスが全く同じならK-meansを終了する。そうでなければ、新しいクラスを元クラスとして2-3を繰り返す。 5. 元画像の各画素で色の距離が最小となるクラスのRGBを割り当てる。 pythonを用いて処理3-5を実装せよ。 # 選ばれた色 [[182.90548706 156.39289856 181.05880737] [157.28413391 124.02828979 136.6774292 ] [228.36817932 201.76049805 211.80619812] [ 91.52492523 57.49259949 56.78660583] [121.73962402 88.02610779 96.16177368]] 減色処理したもの。塗り絵イラスト風な画像にできる。k=10にすればある程度の色を保持しながらもイラスト風に減色できる。 また、k=5にしてmadara.jpgにも試してみよ。
import numpy as np # get IoU overlap ratio def iou(a, b): # get area of a area_a = (a[2] - a[0]) * (a[3] - a[1]) # get area of b area_b = (b[2] - b[0]) * (b[3] - b[1]) # get left top x of IoU iou_x1 = np.maximum(a[0], b[0]) # get left top y of IoU iou_y1 = np.maximum(a[1], b[1]) # get right bottom of IoU iou_x2 = np.minimum(a[2], b[2]) # get right bottom of IoU iou_y2 = np.minimum(a[3], b[3]) # get width of IoU iou_w = iou_x2 - iou_x1 # get height of IoU iou_h = iou_y2 - iou_y1 # get area of IoU area_iou = iou_w * iou_h # get overlap ratio between IoU and all area iou = area_iou / (area_a + area_b - area_iou) return iou # [x1, y1, x2, y2] a = np.array((50, 50, 150, 150), dtype=np.float32) b = np.array((60, 60, 170, 160), dtype=np.float32) print(iou(a, b))
code_generation
292
MIT
gasyori_100_knocks
機械学習で用いる学習データの準備を行う。 最終的にはイモリの顔か否かを判別する識別器を作りたい。そのためにはイモリの顔の画像とイモリの顔以外の画像が必要になる。それらを用意するためのプログラムを作成する。 そのためにはイモリの顔周辺を一枚の画像から切り抜く必要がある。 そこで一つの矩形を設定して(GT: Ground-truth, 正解と呼ぶ)、ランダムに切り抜いた矩形がGTとある程度重なっていれば、イモリの顔となる。 その重なり具合を計算するのが、IoU: Intersection over unionであり、次式で計算される。 R1...Ground-truthの領域 , R2...切り抜いた矩形 , Rol...R1とR2の重なっている領域 IoU = |Rol| / |R1 + R2 - Rol| pythonを用いて、以下の2つの矩形のIoUを計算せよ。 # [x1, y1, x2, y2] x1,y1...矩形の左上のx,y x2,y2...矩形の右下のx,y a = np.array((50, 50, 150, 150), dtype=np.float32) b = np.array((60, 60, 170, 160), dtype=np.float32)
import cv2 import numpy as np np.random.seed(0) # get IoU overlap ratio def iou(a, b): # get area of a area_a = (a[2] - a[0]) * (a[3] - a[1]) # get area of b area_b = (b[2] - b[0]) * (b[3] - b[1]) # get left top x of IoU iou_x1 = np.maximum(a[0], b[0]) # get left top y of IoU iou_y1 = np.maximum(a[1], b[1]) # get right bottom of IoU iou_x2 = np.minimum(a[2], b[2]) # get right bottom of IoU iou_y2 = np.minimum(a[3], b[3]) # get width of IoU iou_w = iou_x2 - iou_x1 # get height of IoU iou_h = iou_y2 - iou_y1 # get area of IoU area_iou = iou_w * iou_h # get overlap ratio between IoU and all area iou = area_iou / (area_a + area_b - area_iou) return iou # crop and create database def crop_bbox(img, gt, Crop_N=200, L=60, th=0.5): # get shape H, W, C = img.shape # each crop for i in range(Crop_N): # get left top x of crop bounding box x1 = np.random.randint(W - L) # get left top y of crop bounding box y1 = np.random.randint(H - L) # get right bottom x of crop bounding box x2 = x1 + L # get right bottom y of crop bounding box y2 = y1 + L # crop bounding box crop = np.array((x1, y1, x2, y2)) # get IoU between crop box and gt _iou = iou(gt, crop) # assign label if _iou >= th: cv2.rectangle(img, (x1, y1), (x2, y2), (0,0,255), 1) label = 1 else: cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 1) label = 0 return img # read image img = cv2.imread("imori_1.jpg") # gt bounding box gt = np.array((47, 41, 129, 103), dtype=np.float32) # get crop bounding box img = crop_bbox(img, gt) # draw gt cv2.rectangle(img, (gt[0], gt[1]), (gt[2], gt[3]), (0,255,0), 1) cv2.imwrite("out.jpg", img) cv2.imshow("result", img) cv2.waitKey(0)
code_generation
293
MIT
gasyori_100_knocks
pythonを用いて、imori_1.jpgからランダムに画像を切り抜いて(cropping, クラッピングと呼ぶ)学習データを作成する。 ここでは画像から60x60のサイズの矩形をランダムに200個切り抜け。 ただし、以下の条件を満たせ。 1. np.random.seed(0)として、切り抜く矩形の左上のx1 = np.random.randint(W-60), y1=np.random.randint(H-60)で求めよ。 2. GT (gt = np.array((47, 41, 129, 103), dtype=np.float32))とのIoUが0.5以上の時はその矩形に教師ラベル1, 0.5未満の場合はラベル0を与えよ。
import numpy as np np.random.seed(0) # neural network class NN: def __init__(self, ind=2, w=64, w2=64, outd=1, lr=0.1): # layer 1 weight self.w1 = np.random.normal(0, 1, [ind, w]) # layer 1 bias self.b1 = np.random.normal(0, 1, [w]) # layer 2 weight self.w2 = np.random.normal(0, 1, [w, w2]) # layer 2 bias self.b2 = np.random.normal(0, 1, [w2]) # output layer weight self.wout = np.random.normal(0, 1, [w2, outd]) # output layer bias self.bout = np.random.normal(0, 1, [outd]) # learning rate self.lr = lr def forward(self, x): # input tensor self.z1 = x # layer 1 output tensor self.z2 = sigmoid(np.dot(self.z1, self.w1) + self.b1) # layer 2 output tensor self.z3 = sigmoid(np.dot(self.z2, self.w2) + self.b2) # output layer tensor self.out = sigmoid(np.dot(self.z3, self.wout) + self.bout) return self.out def train(self, x, t): # backpropagation output layer #En = t * np.log(self.out) + (1-t) * np.log(1-self.out) En = (self.out - t) * self.out * (1 - self.out) # get gradients for weight and bias grad_wout = np.dot(self.z3.T, En) grad_bout = np.dot(np.ones([En.shape[0]]), En) # update weight and bias self.wout -= self.lr * grad_wout self.bout -= self.lr * grad_bout # backpropagation inter layer # get gradients for weight and bias grad_u2 = np.dot(En, self.wout.T) * self.z3 * (1 - self.z3) grad_w2 = np.dot(self.z2.T, grad_u2) grad_b2 = np.dot(np.ones([grad_u2.shape[0]]), grad_u2) # update weight and bias self.w2 -= self.lr * grad_w2 self.b2 -= self.lr * grad_b2 # get gradients for weight and bias grad_u1 = np.dot(grad_u2, self.w2.T) * self.z2 * (1 - self.z2) grad_w1 = np.dot(self.z1.T, grad_u1) grad_b1 = np.dot(np.ones([grad_u1.shape[0]]), grad_u1) # update weight and bias self.w1 -= self.lr * grad_w1 self.b1 -= self.lr * grad_b1 # sigmoid def sigmoid(x): return 1. / (1. + np.exp(-x)) # train def train_nn(nn, train_x, train_t, iteration_N=5000): for i in range(5000): # feed-forward data nn.forward(train_x) #print("ite>>", i, 'y >>', nn.forward(train_x)) # update parameters nn.train(train_x, train_t) return nn # test def test_nn(nn, test_x, test_t): for j in range(len(test_x)): x = train_x[j] t = train_t[j] print("in:", x, "pred:", nn.forward(x)) # train data train_x = np.array([[0,0], [0,1], [1,0], [1,1]], dtype=np.float32) # train label data train_t = np.array([[0], [1], [1], [0]], dtype=np.float32) # prepare neural network nn = NN() # train nn = train_nn(nn, train_x, train_t, iteration_N=5000) # test test_nn(nn, train_x, train_t)
code_generation
294
MIT
gasyori_100_knocks
ニューラルネットワークを用いて識別を行う。 これは現在流行っているディープラーニングである。 入力層、中間層(ユニット数:64)、出力層(1)のネットワークは次のようにプログラムできる。これは、排他的論理和を実現するネットワークである。 import numpy as np np.random.seed(0) class NN: def __init__(self, ind=2, w=64, outd=1, lr=0.1): self.w1 = np.random.normal(0, 1, [ind, w]) self.b1 = np.random.normal(0, 1, [w]) self.wout = np.random.normal(0, 1, [w, outd]) self.bout = np.random.normal(0, 1, [outd]) self.lr = lr def forward(self, x): self.z1 = x self.z2 = sigmoid(np.dot(self.z1, self.w1) + self.b1) self.out = sigmoid(np.dot(self.z2, self.wout) + self.bout) return self.out def train(self, x, t): # backpropagation output layer #En = t * np.log(self.out) + (1-t) * np.log(1-self.out) En = (self.out - t) * self.out * (1 - self.out) grad_En = En #np.array([En for _ in range(t.shape[0])]) grad_wout = np.dot(self.z2.T, En) grad_bout = np.dot(np.ones([En.shape[0]]), En) self.wout -= self.lr * grad_wout#np.expand_dims(grad_wout, axis=-1) self.bout -= self.lr * grad_bout # backpropagation inter layer grad_u1 = np.dot(En, self.wout.T) * self.z2 * (1 - self.z2) grad_w1 = np.dot(self.z1.T, grad_u1) grad_b1 = np.dot(np.ones([grad_u1.shape[0]]), grad_u1) self.w1 -= self.lr * grad_w1 self.b1 -= self.lr * grad_b1 def sigmoid(x): return 1. / (1. + np.exp(-x)) train_x = np.array([[0,0], [0,1], [1,0], [1,1]], dtype=np.float32) train_t = np.array([[0], [1], [1], [0]], dtype=np.float32) nn = NN(ind=train_x.shape[1]) # train for i in range(1000): nn.forward(train_x) nn.train(train_x, train_t) # test for j in range(4): x = train_x[j] t = train_t[j] print("in:", x, "pred:", nn.forward(x)) ここでは、pythonを用いて、中間層(ユニット数:64)をもう一層増やし、学習・テストを行いなさい。
import cv2 import numpy as np np.random.seed(0) # get HOG def HOG(img): # Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Magnitude and gradient def get_gradXY(gray): H, W = gray.shape # padding before grad gray = np.pad(gray, (1, 1), 'edge') # get grad x gx = gray[1:H+1, 2:] - gray[1:H+1, :W] # get grad y gy = gray[2:, 1:W+1] - gray[:H, 1:W+1] # replace 0 with gx[gx == 0] = 1e-6 return gx, gy # get magnitude and gradient def get_MagGrad(gx, gy): # get gradient maginitude magnitude = np.sqrt(gx ** 2 + gy ** 2) # get gradient angle gradient = np.arctan(gy / gx) gradient[gradient < 0] = np.pi / 2 + gradient[gradient < 0] + np.pi / 2 return magnitude, gradient # Gradient histogram def quantization(gradient): # prepare quantization table gradient_quantized = np.zeros_like(gradient, dtype=np.int) # quantization base d = np.pi / 9 # quantization for i in range(9): gradient_quantized[np.where((gradient >= d * i) & (gradient <= d * (i + 1)))] = i return gradient_quantized # get gradient histogram def gradient_histogram(gradient_quantized, magnitude, N=8): # get shape H, W = magnitude.shape # get cell num cell_N_H = H // N cell_N_W = W // N histogram = np.zeros((cell_N_H, cell_N_W, 9), dtype=np.float32) # each pixel for y in range(cell_N_H): for x in range(cell_N_W): for j in range(N): for i in range(N): histogram[y, x, gradient_quantized[y * 4 + j, x * 4 + i]] += magnitude[y * 4 + j, x * 4 + i] return histogram # histogram normalization def normalization(histogram, C=3, epsilon=1): cell_N_H, cell_N_W, _ = histogram.shape ## each histogram for y in range(cell_N_H): for x in range(cell_N_W): #for i in range(9): histogram[y, x] /= np.sqrt(np.sum(histogram[max(y - 1, 0) : min(y + 2, cell_N_H), max(x - 1, 0) : min(x + 2, cell_N_W)] ** 2) + epsilon) return histogram # 1. BGR -> Gray gray = BGR2GRAY(img) # 1. Gray -> Gradient x and y gx, gy = get_gradXY(gray) # 2. get gradient magnitude and angle magnitude, gradient = get_MagGrad(gx, gy) # 3. Quantization gradient_quantized = quantization(gradient) # 4. Gradient histogram histogram = gradient_histogram(gradient_quantized, magnitude) # 5. Histogram normalization histogram = normalization(histogram) return histogram # get IoU overlap ratio def iou(a, b): # get area of a area_a = (a[2] - a[0]) * (a[3] - a[1]) # get area of b area_b = (b[2] - b[0]) * (b[3] - b[1]) # get left top x of IoU iou_x1 = np.maximum(a[0], b[0]) # get left top y of IoU iou_y1 = np.maximum(a[1], b[1]) # get right bottom of IoU iou_x2 = np.minimum(a[2], b[2]) # get right bottom of IoU iou_y2 = np.minimum(a[3], b[3]) # get width of IoU iou_w = iou_x2 - iou_x1 # get height of IoU iou_h = iou_y2 - iou_y1 # get area of IoU area_iou = iou_w * iou_h # get overlap ratio between IoU and all area iou = area_iou / (area_a + area_b - area_iou) return iou # resize using bi-linear def resize(img, h, w): # get shape _h, _w, _c = img.shape # get resize ratio ah = 1. * h / _h aw = 1. * w / _w # get index of each y y = np.arange(h).repeat(w).reshape(w, -1) # get index of each x x = np.tile(np.arange(w), (h, 1)) # get coordinate toward x and y of resized image y = (y / ah) x = (x / aw) # transfer to int ix = np.floor(x).astype(np.int32) iy = np.floor(y).astype(np.int32) # clip index ix = np.minimum(ix, _w-2) iy = np.minimum(iy, _h-2) # get distance between original image index and resized image index dx = x - ix dy = y - iy dx = np.tile(dx, [_c, 1, 1]).transpose(1, 2, 0) dy = np.tile(dy, [_c, 1, 1]).transpose(1, 2, 0) # resize out = (1 - dx) * (1 - dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix + 1] + (1 - dx) * dy * img[iy + 1, ix] + dx * dy * img[iy + 1, ix + 1] out[out > 255] = 255 return out # neural network class NN: def __init__(self, ind=2, w=64, w2=64, outd=1, lr=0.1): # layer 1 weight self.w1 = np.random.normal(0, 1, [ind, w]) # layer 1 bias self.b1 = np.random.normal(0, 1, [w]) # layer 2 weight self.w2 = np.random.normal(0, 1, [w, w2]) # layer 2 bias self.b2 = np.random.normal(0, 1, [w2]) # output layer weight self.wout = np.random.normal(0, 1, [w2, outd]) # output layer bias self.bout = np.random.normal(0, 1, [outd]) # learning rate self.lr = lr def forward(self, x): # input tensor self.z1 = x # layer 1 output tensor self.z2 = sigmoid(np.dot(self.z1, self.w1) + self.b1) # layer 2 output tensor self.z3 = sigmoid(np.dot(self.z2, self.w2) + self.b2) # output layer tensor self.out = sigmoid(np.dot(self.z3, self.wout) + self.bout) return self.out def train(self, x, t): # backpropagation output layer #En = t * np.log(self.out) + (1-t) * np.log(1-self.out) En = (self.out - t) * self.out * (1 - self.out) # get gradients for weight and bias grad_wout = np.dot(self.z3.T, En) grad_bout = np.dot(np.ones([En.shape[0]]), En) # update weight and bias self.wout -= self.lr * grad_wout self.bout -= self.lr * grad_bout # backpropagation inter layer # get gradients for weight and bias grad_u2 = np.dot(En, self.wout.T) * self.z3 * (1 - self.z3) grad_w2 = np.dot(self.z2.T, grad_u2) grad_b2 = np.dot(np.ones([grad_u2.shape[0]]), grad_u2) # update weight and bias self.w2 -= self.lr * grad_w2 self.b2 -= self.lr * grad_b2 # get gradients for weight and bias grad_u1 = np.dot(grad_u2, self.w2.T) * self.z2 * (1 - self.z2) grad_w1 = np.dot(self.z1.T, grad_u1) grad_b1 = np.dot(np.ones([grad_u1.shape[0]]), grad_u1) # update weight and bias self.w1 -= self.lr * grad_w1 self.b1 -= self.lr * grad_b1 # sigmoid def sigmoid(x): return 1. / (1. + np.exp(-x)) # train def train_nn(nn, train_x, train_t, iteration_N=10000): # each iteration for i in range(iteration_N): # feed-forward data nn.forward(train_x) # update parameter nn.train(train_x, train_t) return nn # test def test_nn(nn, test_x, test_t, pred_th=0.5): accuracy_N = 0. # each data for data, t in zip(test_x, test_t): # get prediction prob = nn.forward(data) # count accuracy pred = 1 if prob >= pred_th else 0 if t == pred: accuracy_N += 1 # get accuracy accuracy = accuracy_N / len(db) print("Accuracy >> {} ({} / {})".format(accuracy, accuracy_N, len(db))) # crop bounding box and make dataset def make_dataset(img, gt, Crop_N=200, L=60, th=0.5, H_size=32): # get shape H, W, _ = img.shape # get HOG feature dimension HOG_feature_N = ((H_size // 8) ** 2) * 9 # prepare database db = np.zeros([Crop_N, HOG_feature_N + 1]) # each crop for i in range(Crop_N): # get left top x of crop bounding box x1 = np.random.randint(W - L) # get left top y of crop bounding box y1 = np.random.randint(H - L) # get right bottom x of crop bounding box x2 = x1 + L # get right bottom y of crop bounding box y2 = y1 + L # get bounding box crop = np.array((x1, y1, x2, y2)) _iou = np.zeros((3,)) _iou[0] = iou(gt, crop) #_iou[1] = iou(gt2, crop) #_iou[2] = iou(gt3, crop) # get label if _iou.max() >= th: cv2.rectangle(img, (x1, y1), (x2, y2), (0,0,255), 1) label = 1 else: cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 1) label = 0 # crop area crop_area = img[y1:y2, x1:x2] # resize crop area crop_area = resize(crop_area, H_size, H_size) # get HOG feature _hog = HOG(crop_area) # store HOG feature and label db[i, :HOG_feature_N] = _hog.ravel() db[i, -1] = label return db # Read image img = cv2.imread("imori.jpg").astype(np.float32) # get HOG histogram = HOG(img) # prepare gt bounding box gt = np.array((47, 41, 129, 103), dtype=np.float32) # get database db = make_dataset(img, gt) # train neural network # get input feature dimension input_dim = db.shape[1] - 1 # prepare train data X train_x = db[:, :input_dim] # prepare train data t train_t = db[:, -1][..., None] # prepare neural network nn = NN(ind=input_dim, lr=0.01) # training nn = train_nn(nn, train_x, train_t, iteration_N=10000) # test test_nn(nn, train_x, train_t)
code_generation
295
MIT
gasyori_100_knocks
pythonを用いて、imori_1.jpgからランダムに画像を切り抜いて(cropping, クラッピングと呼ぶ)作成した200個の学習データのHOG特徴量を入力として以下に示すニューラルネットワークを学習せよ。 import numpy as np np.random.seed(0) class NN: def __init__(self, ind=2, w=64, outd=1, lr=0.1): self.w1 = np.random.normal(0, 1, [ind, w]) self.b1 = np.random.normal(0, 1, [w]) self.wout = np.random.normal(0, 1, [w, outd]) self.bout = np.random.normal(0, 1, [outd]) self.lr = lr def forward(self, x): self.z1 = x self.z2 = sigmoid(np.dot(self.z1, self.w1) + self.b1) self.out = sigmoid(np.dot(self.z2, self.wout) + self.bout) return self.out def train(self, x, t): # backpropagation output layer #En = t * np.log(self.out) + (1-t) * np.log(1-self.out) En = (self.out - t) * self.out * (1 - self.out) grad_En = En #np.array([En for _ in range(t.shape[0])]) grad_wout = np.dot(self.z2.T, En) grad_bout = np.dot(np.ones([En.shape[0]]), En) self.wout -= self.lr * grad_wout#np.expand_dims(grad_wout, axis=-1) self.bout -= self.lr * grad_bout # backpropagation inter layer grad_u1 = np.dot(En, self.wout.T) * self.z2 * (1 - self.z2) grad_w1 = np.dot(self.z1.T, grad_u1) grad_b1 = np.dot(np.ones([grad_u1.shape[0]]), grad_u1) self.w1 -= self.lr * grad_w1 self.b1 -= self.lr * grad_b1 def sigmoid(x): return 1. / (1. + np.exp(-x)) train_x = np.array([[0,0], [0,1], [1,0], [1,1]], dtype=np.float32) train_t = np.array([[0], [1], [1], [0]], dtype=np.float32) nn = NN(ind=train_x.shape[1]) # train for i in range(1000): nn.forward(train_x) nn.train(train_x, train_t) # test for j in range(4): x = train_x[j] t = train_t[j] print("in:", x, "pred:", nn.forward(x)) ここでは、学習データに対してAccuracyを計算せよ。ただし、出力(予測確率)が0.5以上で予測ラベルが1、0.5未満で予測ラベルは0としてAccuracyを計算せよ。 学習のハイパーパラメータは、下記の通り。 - 学習率 lr= 0.01 - 学習回数 epch=10000 - 切り抜いた画像を32x32にリサイズして、HOG特徴量を取得せよ。(HOGは8x8を1セルとする。)
import cv2 import numpy as np np.random.seed(0) # get HOG def HOG(img): # Grayscale def BGR2GRAY(img): gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] return gray # Magnitude and gradient def get_gradXY(gray): H, W = gray.shape # padding before grad gray = np.pad(gray, (1, 1), 'edge') # get grad x gx = gray[1:H+1, 2:] - gray[1:H+1, :W] # get grad y gy = gray[2:, 1:W+1] - gray[:H, 1:W+1] # replace 0 with gx[gx == 0] = 1e-6 return gx, gy # get magnitude and gradient def get_MagGrad(gx, gy): # get gradient maginitude magnitude = np.sqrt(gx ** 2 + gy ** 2) # get gradient angle gradient = np.arctan(gy / gx) gradient[gradient < 0] = np.pi / 2 + gradient[gradient < 0] + np.pi / 2 return magnitude, gradient # Gradient histogram def quantization(gradient): # prepare quantization table gradient_quantized = np.zeros_like(gradient, dtype=np.int) # quantization base d = np.pi / 9 # quantization for i in range(9): gradient_quantized[np.where((gradient >= d * i) & (gradient <= d * (i + 1)))] = i return gradient_quantized # get gradient histogram def gradient_histogram(gradient_quantized, magnitude, N=8): # get shape H, W = magnitude.shape # get cell num cell_N_H = H // N cell_N_W = W // N histogram = np.zeros((cell_N_H, cell_N_W, 9), dtype=np.float32) # each pixel for y in range(cell_N_H): for x in range(cell_N_W): for j in range(N): for i in range(N): histogram[y, x, gradient_quantized[y * 4 + j, x * 4 + i]] += magnitude[y * 4 + j, x * 4 + i] return histogram # histogram normalization def normalization(histogram, C=3, epsilon=1): cell_N_H, cell_N_W, _ = histogram.shape ## each histogram for y in range(cell_N_H): for x in range(cell_N_W): #for i in range(9): histogram[y, x] /= np.sqrt(np.sum(histogram[max(y - 1, 0) : min(y + 2, cell_N_H), max(x - 1, 0) : min(x + 2, cell_N_W)] ** 2) + epsilon) return histogram # 1. BGR -> Gray gray = BGR2GRAY(img) # 1. Gray -> Gradient x and y gx, gy = get_gradXY(gray) # 2. get gradient magnitude and angle magnitude, gradient = get_MagGrad(gx, gy) # 3. Quantization gradient_quantized = quantization(gradient) # 4. Gradient histogram histogram = gradient_histogram(gradient_quantized, magnitude) # 5. Histogram normalization histogram = normalization(histogram) return histogram # get IoU overlap ratio def iou(a, b): # get area of a area_a = (a[2] - a[0]) * (a[3] - a[1]) # get area of b area_b = (b[2] - b[0]) * (b[3] - b[1]) # get left top x of IoU iou_x1 = np.maximum(a[0], b[0]) # get left top y of IoU iou_y1 = np.maximum(a[1], b[1]) # get right bottom of IoU iou_x2 = np.minimum(a[2], b[2]) # get right bottom of IoU iou_y2 = np.minimum(a[3], b[3]) # get width of IoU iou_w = iou_x2 - iou_x1 # get height of IoU iou_h = iou_y2 - iou_y1 # get area of IoU area_iou = iou_w * iou_h # get overlap ratio between IoU and all area iou = area_iou / (area_a + area_b - area_iou) return iou # resize using bi-linear def resize(img, h, w): # get shape _h, _w, _c = img.shape # get resize ratio ah = 1. * h / _h aw = 1. * w / _w # get index of each y y = np.arange(h).repeat(w).reshape(w, -1) # get index of each x x = np.tile(np.arange(w), (h, 1)) # get coordinate toward x and y of resized image y = (y / ah) x = (x / aw) # transfer to int ix = np.floor(x).astype(np.int32) iy = np.floor(y).astype(np.int32) # clip index ix = np.minimum(ix, _w-2) iy = np.minimum(iy, _h-2) # get distance between original image index and resized image index dx = x - ix dy = y - iy dx = np.tile(dx, [_c, 1, 1]).transpose(1, 2, 0) dy = np.tile(dy, [_c, 1, 1]).transpose(1, 2, 0) # resize out = (1 - dx) * (1 - dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix + 1] + (1 - dx) * dy * img[iy + 1, ix] + dx * dy * img[iy + 1, ix + 1] out[out > 255] = 255 return out # sliding window def sliding_window(img, H_size=32): # get shape H, W, _ = img.shape # base rectangle [h, w] recs = np.array(((42, 42), (56, 56), (70, 70)), dtype=np.float32) # sliding window for y in range(0, H, 4): for x in range(0, W, 4): for rec in recs: # get half size of ractangle dh = int(rec[0] // 2) dw = int(rec[1] // 2) # get left top x x1 = max(x - dw, 0) # get left top y x2 = min(x + dw, W) # get right bottom x y1 = max(y - dh, 0) # get right bottom y y2 = min(y + dh, H) # crop region region = img[max(y - dh, 0) : min(y + dh, H), max(x - dw, 0) : min(x + dw, W)] # resize crop region region = resize(region, H_size, H_size) # get HOG feature region_hog = HOG(region).ravel() # read detect target image img = cv2.imread("imori_many.jpg") sliding_window(img)
code_generation
296
MIT
gasyori_100_knocks
pythonを用いて、物体検出を行う。 物体検出とは、画像中でどこに何が写っているかを出力するタスクである。 例えば、画像の[x1, y1, x2, y2]の位置に犬がいるなど。 このような物体を囲む矩形のことをBounding-box(バウンディングボックス)と呼ぶ。 ここでは簡単な物体検出のアルゴリズムを作成する。 1. 画像の左上からスライディングウィンドウを行う。 2. 各画像の位置について、注目位置を中心に複数の矩形を用意する。 3. それぞれの矩形に対応する画像を切り抜いて、特徴抽出(HOG, SIFTなど)を行う。 4. 識別機(CNN, SVMなど)に掛けて各矩形が物体か否かを判別する。 これである程度の物体と矩形の座標が得られる。現在は物体検出はディープラーニングによる手法(Faster R-CNN, YOLO, SSDなど)が主流であるが、ディープラーニングが流行る前まではこのようなスライディングウィンドウの手法が主流であった。今回は検出の基礎を学ぶため、スライディングウィンドウを扱う。 ここではpythonで処理1-3を実装しなさい。 imori_many.jpgに対してイモリの顔検出を行う。 条件は以下。 - 矩形は下記のものを用いる。 # [h, w] recs = np.array(((42, 42), (56, 56), (70, 70)), dtype=np.float32) - スライドは4ピクセルおきに行う。(1ピクセルでもいいが、計算が多くなって処理が長くなってしまう。) - 矩形が画像サイズをはみ出る場合は、はみ出ないように変形する。 - 矩形部分を切り抜いたら、その部分を32x32にリサイズする。 - HOG特徴量の取得は8x8を1セルとする。
import cv2 import numpy as np np.random.seed(0) # read image img = cv2.imread("imori_1.jpg") H, W, C = img.shape # Grayscale gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] gt = np.array((47, 41, 129, 103), dtype=np.float32) cv2.rectangle(img, (gt[0], gt[1]), (gt[2], gt[3]), (0,255,255), 1) def iou(a, b): area_a = (a[2] - a[0]) * (a[3] - a[1]) area_b = (b[2] - b[0]) * (b[3] - b[1]) iou_x1 = np.maximum(a[0], b[0]) iou_y1 = np.maximum(a[1], b[1]) iou_x2 = np.minimum(a[2], b[2]) iou_y2 = np.minimum(a[3], b[3]) iou_w = max(iou_x2 - iou_x1, 0) iou_h = max(iou_y2 - iou_y1, 0) area_iou = iou_w * iou_h iou = area_iou / (area_a + area_b - area_iou) return iou def hog(gray): h, w = gray.shape # Magnitude and gradient gray = np.pad(gray, (1, 1), 'edge') gx = gray[1:h+1, 2:] - gray[1:h+1, :w] gy = gray[2:, 1:w+1] - gray[:h, 1:w+1] gx[gx == 0] = 0.000001 mag = np.sqrt(gx ** 2 + gy ** 2) gra = np.arctan(gy / gx) gra[gra<0] = np.pi / 2 + gra[gra < 0] + np.pi / 2 # Gradient histogram gra_n = np.zeros_like(gra, dtype=np.int) d = np.pi / 9 for i in range(9): gra_n[np.where((gra >= d * i) & (gra <= d * (i+1)))] = i N = 8 HH = h // N HW = w // N Hist = np.zeros((HH, HW, 9), dtype=np.float32) for y in range(HH): for x in range(HW): for j in range(N): for i in range(N): Hist[y, x, gra_n[y*4+j, x*4+i]] += mag[y*4+j, x*4+i] ## Normalization C = 3 eps = 1 for y in range(HH): for x in range(HW): #for i in range(9): Hist[y, x] /= np.sqrt(np.sum(Hist[max(y-1,0):min(y+2, HH), max(x-1,0):min(x+2, HW)] ** 2) + eps) return Hist def resize(img, h, w): _h, _w = img.shape ah = 1. * h / _h aw = 1. * w / _w y = np.arange(h).repeat(w).reshape(w, -1) x = np.tile(np.arange(w), (h, 1)) y = (y / ah) x = (x / aw) ix = np.floor(x).astype(np.int32) iy = np.floor(y).astype(np.int32) ix = np.minimum(ix, _w-2) iy = np.minimum(iy, _h-2) dx = x - ix dy = y - iy out = (1-dx) * (1-dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix+1] + (1 - dx) * dy * img[iy+1, ix] + dx * dy * img[iy+1, ix+1] out[out>255] = 255 return out class NN: def __init__(self, ind=2, w=64, w2=64, outd=1, lr=0.1): self.w1 = np.random.normal(0, 1, [ind, w]) self.b1 = np.random.normal(0, 1, [w]) self.w2 = np.random.normal(0, 1, [w, w2]) self.b2 = np.random.normal(0, 1, [w2]) self.wout = np.random.normal(0, 1, [w2, outd]) self.bout = np.random.normal(0, 1, [outd]) self.lr = lr def forward(self, x): self.z1 = x self.z2 = sigmoid(np.dot(self.z1, self.w1) + self.b1) self.z3 = sigmoid(np.dot(self.z2, self.w2) + self.b2) self.out = sigmoid(np.dot(self.z3, self.wout) + self.bout) return self.out def train(self, x, t): # backpropagation output layer #En = t * np.log(self.out) + (1-t) * np.log(1-self.out) En = (self.out - t) * self.out * (1 - self.out) grad_wout = np.dot(self.z3.T, En) grad_bout = np.dot(np.ones([En.shape[0]]), En) self.wout -= self.lr * grad_wout self.bout -= self.lr * grad_bout # backpropagation inter layer grad_u2 = np.dot(En, self.wout.T) * self.z3 * (1 - self.z3) grad_w2 = np.dot(self.z2.T, grad_u2) grad_b2 = np.dot(np.ones([grad_u2.shape[0]]), grad_u2) self.w2 -= self.lr * grad_w2 self.b2 -= self.lr * grad_b2 grad_u1 = np.dot(grad_u2, self.w2.T) * self.z2 * (1 - self.z2) grad_w1 = np.dot(self.z1.T, grad_u1) grad_b1 = np.dot(np.ones([grad_u1.shape[0]]), grad_u1) self.w1 -= self.lr * grad_w1 self.b1 -= self.lr * grad_b1 def sigmoid(x): return 1. / (1. + np.exp(-x)) # crop and create database Crop_num = 200 L = 60 H_size = 32 F_n = ((H_size // 8) ** 2) * 9 db = np.zeros((Crop_num, F_n+1)) for i in range(Crop_num): x1 = np.random.randint(W-L) y1 = np.random.randint(H-L) x2 = x1 + L y2 = y1 + L crop = np.array((x1, y1, x2, y2)) _iou = iou(gt, crop) if _iou >= 0.5: cv2.rectangle(img, (x1, y1), (x2, y2), (0,0,255), 1) label = 1 else: cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 1) label = 0 crop_area = gray[y1:y2, x1:x2] crop_area = resize(crop_area, H_size, H_size) _hog = hog(crop_area) db[i, :F_n] = _hog.ravel() db[i, -1] = label ## train neural network nn = NN(ind=F_n, lr=0.01) for i in range(10000): nn.forward(db[:, :F_n]) nn.train(db[:, :F_n], db[:, -1][..., None]) # read detect target image img2 = cv2.imread("imori_many.jpg") H2, W2, C2 = img2.shape # Grayscale gray2 = 0.2126 * img2[..., 2] + 0.7152 * img2[..., 1] + 0.0722 * img2[..., 0] # [h, w] recs = np.array(((42, 42), (56, 56), (70, 70)), dtype=np.float32) detects = np.ndarray((0, 5), dtype=np.float32) # sliding window for y in range(0, H2, 4): for x in range(0, W2, 4): for rec in recs: dh = int(rec[0] // 2) dw = int(rec[1] // 2) x1 = max(x-dw, 0) x2 = min(x+dw, W2) y1 = max(y-dh, 0) y2 = min(y+dh, H2) region = gray2[max(y-dh,0):min(y+dh,H2), max(x-dw,0):min(x+dw,W2)] region = resize(region, H_size, H_size) region_hog = hog(region).ravel() score = nn.forward(region_hog) if score >= 0.7: cv2.rectangle(img2, (x1, y1), (x2, y2), (0,0,255), 1) detects = np.vstack((detects, np.array((x1, y1, x2, y2, score)))) print(detects) cv2.imwrite("out.jpg", img2) cv2.imshow("result", img2) cv2.waitKey(0)
code_generation
297
MIT
gasyori_100_knocks
pythonを用いて、imori_many.jpgの物体検出で求めたが各矩形のHOG特徴量を入力として、以下のニューラルネットでイモリの顔か否かを識別せよ。また、スコア(予測確率)が0.7以上の矩形を描画せよ。 import numpy as np np.random.seed(0) class NN: def __init__(self, ind=2, w=64, outd=1, lr=0.1): self.w1 = np.random.normal(0, 1, [ind, w]) self.b1 = np.random.normal(0, 1, [w]) self.wout = np.random.normal(0, 1, [w, outd]) self.bout = np.random.normal(0, 1, [outd]) self.lr = lr def forward(self, x): self.z1 = x self.z2 = sigmoid(np.dot(self.z1, self.w1) + self.b1) self.out = sigmoid(np.dot(self.z2, self.wout) + self.bout) return self.out def train(self, x, t): # backpropagation output layer #En = t * np.log(self.out) + (1-t) * np.log(1-self.out) En = (self.out - t) * self.out * (1 - self.out) grad_En = En #np.array([En for _ in range(t.shape[0])]) grad_wout = np.dot(self.z2.T, En) grad_bout = np.dot(np.ones([En.shape[0]]), En) self.wout -= self.lr * grad_wout#np.expand_dims(grad_wout, axis=-1) self.bout -= self.lr * grad_bout # backpropagation inter layer grad_u1 = np.dot(En, self.wout.T) * self.z2 * (1 - self.z2) grad_w1 = np.dot(self.z1.T, grad_u1) grad_b1 = np.dot(np.ones([grad_u1.shape[0]]), grad_u1) self.w1 -= self.lr * grad_w1 self.b1 -= self.lr * grad_b1 def sigmoid(x): return 1. / (1. + np.exp(-x)) train_x = np.array([[0,0], [0,1], [1,0], [1,1]], dtype=np.float32) train_t = np.array([[0], [1], [1], [0]], dtype=np.float32) nn = NN(ind=train_x.shape[1]) # train for i in range(1000): nn.forward(train_x) nn.train(train_x, train_t) # test for j in range(4): x = train_x[j] t = train_t[j] print("in:", x, "pred:", nn.forward(x))
import cv2 import numpy as np np.random.seed(0) # read image img = cv2.imread("imori_1.jpg") H, W, C = img.shape # Grayscale gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] gt = np.array((47, 41, 129, 103), dtype=np.float32) cv2.rectangle(img, (gt[0], gt[1]), (gt[2], gt[3]), (0,255,255), 1) def iou(a, b): area_a = (a[2] - a[0]) * (a[3] - a[1]) area_b = (b[2] - b[0]) * (b[3] - b[1]) iou_x1 = np.maximum(a[0], b[0]) iou_y1 = np.maximum(a[1], b[1]) iou_x2 = np.minimum(a[2], b[2]) iou_y2 = np.minimum(a[3], b[3]) iou_w = max(iou_x2 - iou_x1, 0) iou_h = max(iou_y2 - iou_y1, 0) area_iou = iou_w * iou_h iou = area_iou / (area_a + area_b - area_iou) return iou def hog(gray): h, w = gray.shape # Magnitude and gradient gray = np.pad(gray, (1, 1), 'edge') gx = gray[1:h+1, 2:] - gray[1:h+1, :w] gy = gray[2:, 1:w+1] - gray[:h, 1:w+1] gx[gx == 0] = 0.000001 mag = np.sqrt(gx ** 2 + gy ** 2) gra = np.arctan(gy / gx) gra[gra<0] = np.pi / 2 + gra[gra < 0] + np.pi / 2 # Gradient histogram gra_n = np.zeros_like(gra, dtype=np.int) d = np.pi / 9 for i in range(9): gra_n[np.where((gra >= d * i) & (gra <= d * (i+1)))] = i N = 8 HH = h // N HW = w // N Hist = np.zeros((HH, HW, 9), dtype=np.float32) for y in range(HH): for x in range(HW): for j in range(N): for i in range(N): Hist[y, x, gra_n[y*4+j, x*4+i]] += mag[y*4+j, x*4+i] ## Normalization C = 3 eps = 1 for y in range(HH): for x in range(HW): #for i in range(9): Hist[y, x] /= np.sqrt(np.sum(Hist[max(y-1,0):min(y+2, HH), max(x-1,0):min(x+2, HW)] ** 2) + eps) return Hist def resize(img, h, w): _h, _w = img.shape ah = 1. * h / _h aw = 1. * w / _w y = np.arange(h).repeat(w).reshape(w, -1) x = np.tile(np.arange(w), (h, 1)) y = (y / ah) x = (x / aw) ix = np.floor(x).astype(np.int32) iy = np.floor(y).astype(np.int32) ix = np.minimum(ix, _w-2) iy = np.minimum(iy, _h-2) dx = x - ix dy = y - iy out = (1-dx) * (1-dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix+1] + (1 - dx) * dy * img[iy+1, ix] + dx * dy * img[iy+1, ix+1] out[out>255] = 255 return out # crop and create database Crop_num = 200 L = 60 H_size = 32 F_n = ((H_size // 8) ** 2) * 9 db = np.zeros((Crop_num, F_n+1)) for i in range(Crop_num): x1 = np.random.randint(W-L) y1 = np.random.randint(H-L) x2 = x1 + L y2 = y1 + L crop = np.array((x1, y1, x2, y2)) _iou = iou(gt, crop) if _iou >= 0.5: cv2.rectangle(img, (x1, y1), (x2, y2), (0,0,255), 1) label = 1 else: cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 1) label = 0 crop_area = gray[y1:y2, x1:x2] crop_area = resize(crop_area, H_size, H_size) _hog = hog(crop_area) db[i, :F_n] = _hog.ravel() db[i, -1] = label class NN: def __init__(self, ind=2, w=64, w2=64, outd=1, lr=0.1): self.w1 = np.random.normal(0, 1, [ind, w]) self.b1 = np.random.normal(0, 1, [w]) self.w2 = np.random.normal(0, 1, [w, w2]) self.b2 = np.random.normal(0, 1, [w2]) self.wout = np.random.normal(0, 1, [w2, outd]) self.bout = np.random.normal(0, 1, [outd]) self.lr = lr def forward(self, x): self.z1 = x self.z2 = sigmoid(np.dot(self.z1, self.w1) + self.b1) self.z3 = sigmoid(np.dot(self.z2, self.w2) + self.b2) self.out = sigmoid(np.dot(self.z3, self.wout) + self.bout) return self.out def train(self, x, t): # backpropagation output layer #En = t * np.log(self.out) + (1-t) * np.log(1-self.out) En = (self.out - t) * self.out * (1 - self.out) grad_wout = np.dot(self.z3.T, En) grad_bout = np.dot(np.ones([En.shape[0]]), En) self.wout -= self.lr * grad_wout self.bout -= self.lr * grad_bout # backpropagation inter layer grad_u2 = np.dot(En, self.wout.T) * self.z3 * (1 - self.z3) grad_w2 = np.dot(self.z2.T, grad_u2) grad_b2 = np.dot(np.ones([grad_u2.shape[0]]), grad_u2) self.w2 -= self.lr * grad_w2 self.b2 -= self.lr * grad_b2 grad_u1 = np.dot(grad_u2, self.w2.T) * self.z2 * (1 - self.z2) grad_w1 = np.dot(self.z1.T, grad_u1) grad_b1 = np.dot(np.ones([grad_u1.shape[0]]), grad_u1) self.w1 -= self.lr * grad_w1 self.b1 -= self.lr * grad_b1 def sigmoid(x): return 1. / (1. + np.exp(-x)) ## training neural network nn = NN(ind=F_n, lr=0.01) for i in range(10000): nn.forward(db[:, :F_n]) nn.train(db[:, :F_n], db[:, -1][..., None]) # read detect target image img2 = cv2.imread("imori_many.jpg") H2, W2, C2 = img2.shape # Grayscale gray2 = 0.2126 * img2[..., 2] + 0.7152 * img2[..., 1] + 0.0722 * img2[..., 0] # [h, w] recs = np.array(((42, 42), (56, 56), (70, 70)), dtype=np.float32) detects = np.ndarray((0, 5), dtype=np.float32) # sliding window for y in range(0, H2, 4): for x in range(0, W2, 4): for rec in recs: dh = int(rec[0] // 2) dw = int(rec[1] // 2) x1 = max(x-dw, 0) x2 = min(x+dw, W2) y1 = max(y-dh, 0) y2 = min(y+dh, H2) region = gray2[max(y-dh,0):min(y+dh,H2), max(x-dw,0):min(x+dw,W2)] region = resize(region, H_size, H_size) region_hog = hog(region).ravel() score = nn.forward(region_hog) if score >= 0.7: #cv2.rectangle(img2, (x1, y1), (x2, y2), (0,0,255), 1) detects = np.vstack((detects, np.array((x1, y1, x2, y2, score)))) # Non-maximum suppression def nms(_bboxes, iou_th=0.5, select_num=None, prob_th=None): # # Non Maximum Suppression # # Argument # bboxes(Nx5) ... [bbox-num, 5(leftTopX,leftTopY,w,h, score)] # iou_th([float]) ... threshold for iou between bboxes. # select_num([int]) ... max number for choice bboxes. If None, this is unvalid. # prob_th([float]) ... probability threshold to choice. If None, this is unvalid. # Return # inds ... choced indices for bboxes # bboxes = _bboxes.copy() bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0] bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1] # Sort by bbox's score. High -> Low sort_inds = np.argsort(bboxes[:, -1])[::-1] processed_bbox_ind = [] return_inds = [] unselected_inds = sort_inds.copy() while len(unselected_inds) > 0: process_bboxes = bboxes[unselected_inds] argmax_score_ind = np.argmax(process_bboxes[::, -1]) max_score_ind = unselected_inds[argmax_score_ind] return_inds += [max_score_ind] unselected_inds = np.delete(unselected_inds, argmax_score_ind) base_bbox = bboxes[max_score_ind] compare_bboxes = bboxes[unselected_inds] base_x1 = base_bbox[0] base_y1 = base_bbox[1] base_x2 = base_bbox[2] + base_x1 base_y2 = base_bbox[3] + base_y1 base_w = np.maximum(base_bbox[2], 0) base_h = np.maximum(base_bbox[3], 0) base_area = base_w * base_h # compute iou-area between base bbox and other bboxes iou_x1 = np.maximum(base_x1, compare_bboxes[:, 0]) iou_y1 = np.maximum(base_y1, compare_bboxes[:, 1]) iou_x2 = np.minimum(base_x2, compare_bboxes[:, 2] + compare_bboxes[:, 0]) iou_y2 = np.minimum(base_y2, compare_bboxes[:, 3] + compare_bboxes[:, 1]) iou_w = np.maximum(iou_x2 - iou_x1, 0) iou_h = np.maximum(iou_y2 - iou_y1, 0) iou_area = iou_w * iou_h compare_w = np.maximum(compare_bboxes[:, 2], 0) compare_h = np.maximum(compare_bboxes[:, 3], 0) compare_area = compare_w * compare_h # bbox's index which iou ratio over threshold is excluded all_area = compare_area + base_area - iou_area iou_ratio = np.zeros((len(unselected_inds))) iou_ratio[all_area < 0.9] = 0. _ind = all_area >= 0.9 iou_ratio[_ind] = iou_area[_ind] / all_area[_ind] unselected_inds = np.delete(unselected_inds, np.where(iou_ratio >= iou_th)[0]) if prob_th is not None: preds = bboxes[return_inds][:, -1] return_inds = np.array(return_inds)[np.where(preds >= prob_th)[0]].tolist() # pick bbox's index by defined number with higher score if select_num is not None: return_inds = return_inds[:select_num] return return_inds detects = detects[nms(detects, iou_th=0.25)] for d in detects: v = list(map(int, d[:4])) cv2.rectangle(img2, (v[0], v[1]), (v[2], v[3]), (0,0,255), 1) cv2.putText(img2, "{:.2f}".format(d[-1]), (v[0], v[1]+9), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,0,255), 1) cv2.imwrite("out.jpg", img2) cv2.imshow("result", img2) cv2.waitKey(0)
code_generation
298
MIT
gasyori_100_knocks
ある物体検出にてあらかたの検出はできたが、このままではBounding-boxの数が多すぎて、ここから何かしらの処理に繋げるには不便である。 そこで、NMS: Non-maximum suppressionという手法を用いて矩形の数を減らしなさい。 NMSとはスコアの高いBounding-boxのみを残す手法であり、アルゴリズムは以下の通り。 1. Boundinb-boxの集合Bをスコアが高い順にソートする。 2. スコアが最大のものをb0とする。 3. b0と他のBounding-boxのIoUを計算する。IoUが閾値t以上のBounding-boxをBから削除する。B0は出力する集合Rに加え、Bから削除する。 4. 2-3をBがなくなるまで行う。 5. Rを出力する。 以下のニューラルネットにNMS(閾値t=0.25)を組み込み、出力を描画せよ。
import cv2 import numpy as np np.random.seed(0) # read image img = cv2.imread("imori_1.jpg") H, W, C = img.shape # Grayscale gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0] gt = np.array((47, 41, 129, 103), dtype=np.float32) cv2.rectangle(img, (gt[0], gt[1]), (gt[2], gt[3]), (0,255,255), 1) def iou(a, b): area_a = (a[2] - a[0]) * (a[3] - a[1]) area_b = (b[2] - b[0]) * (b[3] - b[1]) iou_x1 = np.maximum(a[0], b[0]) iou_y1 = np.maximum(a[1], b[1]) iou_x2 = np.minimum(a[2], b[2]) iou_y2 = np.minimum(a[3], b[3]) iou_w = max(iou_x2 - iou_x1, 0) iou_h = max(iou_y2 - iou_y1, 0) area_iou = iou_w * iou_h iou = area_iou / (area_a + area_b - area_iou) return iou def hog(gray): h, w = gray.shape # Magnitude and gradient gray = np.pad(gray, (1, 1), 'edge') gx = gray[1:h+1, 2:] - gray[1:h+1, :w] gy = gray[2:, 1:w+1] - gray[:h, 1:w+1] gx[gx == 0] = 0.000001 mag = np.sqrt(gx ** 2 + gy ** 2) gra = np.arctan(gy / gx) gra[gra<0] = np.pi / 2 + gra[gra < 0] + np.pi / 2 # Gradient histogram gra_n = np.zeros_like(gra, dtype=np.int) d = np.pi / 9 for i in range(9): gra_n[np.where((gra >= d * i) & (gra <= d * (i+1)))] = i N = 8 HH = h // N HW = w // N Hist = np.zeros((HH, HW, 9), dtype=np.float32) for y in range(HH): for x in range(HW): for j in range(N): for i in range(N): Hist[y, x, gra_n[y*4+j, x*4+i]] += mag[y*4+j, x*4+i] ## Normalization C = 3 eps = 1 for y in range(HH): for x in range(HW): #for i in range(9): Hist[y, x] /= np.sqrt(np.sum(Hist[max(y-1,0):min(y+2, HH), max(x-1,0):min(x+2, HW)] ** 2) + eps) return Hist def resize(img, h, w): _h, _w = img.shape ah = 1. * h / _h aw = 1. * w / _w y = np.arange(h).repeat(w).reshape(w, -1) x = np.tile(np.arange(w), (h, 1)) y = (y / ah) x = (x / aw) ix = np.floor(x).astype(np.int32) iy = np.floor(y).astype(np.int32) ix = np.minimum(ix, _w-2) iy = np.minimum(iy, _h-2) dx = x - ix dy = y - iy out = (1-dx) * (1-dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix+1] + (1 - dx) * dy * img[iy+1, ix] + dx * dy * img[iy+1, ix+1] out[out>255] = 255 return out class NN: def __init__(self, ind=2, w=64, w2=64, outd=1, lr=0.1): self.w2 = np.random.randn(ind, w) self.b2 = np.random.randn(w) self.w3 = np.random.randn(w, w2) self.b3 = np.random.randn(w2) self.wout = np.random.randn(w2, outd) self.bout = np.random.randn(outd) self.lr = lr def forward(self, x): self.z1 = x self.z2 = self.sigmoid(np.dot(self.z1, self.w2) + self.b2) self.z3 = self.sigmoid(np.dot(self.z2, self.w3) + self.b3) self.out = self.sigmoid(np.dot(self.z3, self.wout) + self.bout) return self.out def train(self, x, t): # backpropagation output layer out_d = 2*(self.out - t) * self.out * (1 - self.out) out_dW = np.dot(self.z3.T, out_d) out_dB = np.dot(np.ones([1, out_d.shape[0]]), out_d) self.wout -= self.lr * out_dW self.bout -= self.lr * out_dB[0] w3_d = np.dot(out_d, self.wout.T) * self.z3 * (1 - self.z3) w3_dW = np.dot(self.z2.T, w3_d) w3_dB = np.dot(np.ones([1, w3_d.shape[0]]), w3_d) self.w3 -= self.lr * w3_dW self.b3 -= self.lr * w3_dB[0] # backpropagation inter layer w2_d = np.dot(w3_d, self.w3.T) * self.z2 * (1 - self.z2) w2_dW = np.dot(self.z1.T, w2_d) w2_dB = np.dot(np.ones([1, w2_d.shape[0]]), w2_d) self.w2 -= self.lr * w2_dW self.b2 -= self.lr * w2_dB[0] def sigmoid(self, x): return 1. / (1. + np.exp(-x)) # crop and create database Crop_num = 200 L = 60 H_size = 32 F_n = ((H_size // 8) ** 2) * 9 db = np.zeros((Crop_num, F_n+1)) for i in range(Crop_num): x1 = np.random.randint(W-L) y1 = np.random.randint(H-L) x2 = x1 + L y2 = y1 + L crop = np.array((x1, y1, x2, y2)) _iou = iou(gt, crop) if _iou >= 0.5: cv2.rectangle(img, (x1, y1), (x2, y2), (0,0,255), 1) label = 1 else: cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 1) label = 0 crop_area = gray[y1:y2, x1:x2] crop_area = resize(crop_area, H_size, H_size) _hog = hog(crop_area) db[i, :F_n] = _hog.ravel() db[i, -1] = label ## training neural network nn = NN(ind=F_n, lr=0.01) for i in range(10000): nn.forward(db[:, :F_n]) nn.train(db[:, :F_n], db[:, -1][..., None]) # read detect target image img2 = cv2.imread("imori_many.jpg") H2, W2, C2 = img2.shape # Grayscale gray2 = 0.2126 * img2[..., 2] + 0.7152 * img2[..., 1] + 0.0722 * img2[..., 0] # [h, w] recs = np.array(((42, 42), (56, 56), (70, 70)), dtype=np.float32) detects = np.ndarray((0, 5), dtype=np.float32) # sliding window for y in range(0, H2, 4): for x in range(0, W2, 4): for rec in recs: dh = int(rec[0] // 2) dw = int(rec[1] // 2) x1 = max(x-dw, 0) x2 = min(x+dw, W2) y1 = max(y-dh, 0) y2 = min(y+dh, H2) region = gray2[max(y-dh,0):min(y+dh,H2), max(x-dw,0):min(x+dw,W2)] region = resize(region, H_size, H_size) region_hog = hog(region).ravel() score = nn.forward(region_hog) if score >= 0.7: #cv2.rectangle(img2, (x1, y1), (x2, y2), (0,0,255), 1) detects = np.vstack((detects, np.array((x1, y1, x2, y2, score)))) # Non-maximum suppression def nms(_bboxes, iou_th=0.5, select_num=None, prob_th=None): # # Non Maximum Suppression # # Argument # bboxes(Nx5) ... [bbox-num, 5(leftTopX,leftTopY,w,h, score)] # iou_th([float]) ... threshold for iou between bboxes. # select_num([int]) ... max number for choice bboxes. If None, this is unvalid. # prob_th([float]) ... probability threshold to choice. If None, this is unvalid. # Return # inds ... choced indices for bboxes # bboxes = _bboxes.copy() bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0] bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1] # Sort by bbox's score. High -> Low sort_inds = np.argsort(bboxes[:, -1])[::-1] processed_bbox_ind = [] return_inds = [] unselected_inds = sort_inds.copy() while len(unselected_inds) > 0: process_bboxes = bboxes[unselected_inds] argmax_score_ind = np.argmax(process_bboxes[::, -1]) max_score_ind = unselected_inds[argmax_score_ind] return_inds += [max_score_ind] unselected_inds = np.delete(unselected_inds, argmax_score_ind) base_bbox = bboxes[max_score_ind] compare_bboxes = bboxes[unselected_inds] base_x1 = base_bbox[0] base_y1 = base_bbox[1] base_x2 = base_bbox[2] + base_x1 base_y2 = base_bbox[3] + base_y1 base_w = np.maximum(base_bbox[2], 0) base_h = np.maximum(base_bbox[3], 0) base_area = base_w * base_h # compute iou-area between base bbox and other bboxes iou_x1 = np.maximum(base_x1, compare_bboxes[:, 0]) iou_y1 = np.maximum(base_y1, compare_bboxes[:, 1]) iou_x2 = np.minimum(base_x2, compare_bboxes[:, 2] + compare_bboxes[:, 0]) iou_y2 = np.minimum(base_y2, compare_bboxes[:, 3] + compare_bboxes[:, 1]) iou_w = np.maximum(iou_x2 - iou_x1, 0) iou_h = np.maximum(iou_y2 - iou_y1, 0) iou_area = iou_w * iou_h compare_w = np.maximum(compare_bboxes[:, 2], 0) compare_h = np.maximum(compare_bboxes[:, 3], 0) compare_area = compare_w * compare_h # bbox's index which iou ratio over threshold is excluded all_area = compare_area + base_area - iou_area iou_ratio = np.zeros((len(unselected_inds))) iou_ratio[all_area < 0.9] = 0. _ind = all_area >= 0.9 iou_ratio[_ind] = iou_area[_ind] / all_area[_ind] unselected_inds = np.delete(unselected_inds, np.where(iou_ratio >= iou_th)[0]) if prob_th is not None: preds = bboxes[return_inds][:, -1] return_inds = np.array(return_inds)[np.where(preds >= prob_th)[0]].tolist() # pick bbox's index by defined number with higher score if select_num is not None: return_inds = return_inds[:select_num] return return_inds detects = detects[nms(detects, iou_th=0.25)] # Evaluation # [x1, y1, x2, y2] GT = np.array(((27, 48, 95, 110), (101, 75, 171, 138)), dtype=np.float32) ## Recall, Precision, F-score iou_th = 0.5 Rs = np.zeros((len(GT))) Ps = np.zeros((len(detects))) for i, g in enumerate(GT): iou_x1 = np.maximum(g[0], detects[:, 0]) iou_y1 = np.maximum(g[1], detects[:, 1]) iou_x2 = np.minimum(g[2], detects[:, 2]) iou_y2 = np.minimum(g[3], detects[:, 3]) iou_w = np.maximum(0, iou_x2 - iou_x1) iou_h = np.maximum(0, iou_y2 - iou_y1) iou_area = iou_w * iou_h g_area = (g[2] - g[0]) * (g[3] - g[1]) d_area = (detects[:, 2] - detects[:, 0]) * (detects[:, 3] - detects[:, 1]) ious = iou_area / (g_area + d_area - iou_area) Rs[i] = 1 if len(np.where(ious >= iou_th)[0]) > 0 else 0 Ps[ious >= iou_th] = 1 R = np.sum(Rs) / len(Rs) P = np.sum(Ps) / len(Ps) F = (2 * P * R) / (P + R) print("Recall >> {:.2f} ({} / {})".format(R, np.sum(Rs), len(Rs))) print("Precision >> {:.2f} ({} / {})".format(P, np.sum(Ps), len(Ps))) print("F-score >> ", F) ## mAP mAP = 0. for i in range(len(detects)): mAP += np.sum(Ps[:i]) / (i + 1) * Ps[i] mAP /= np.sum(Ps) print("mAP >>", mAP) # Display for i in range(len(detects)): v = list(map(int, detects[i, :4])) if Ps[i] > 0: cv2.rectangle(img2, (v[0], v[1]), (v[2], v[3]), (0,0,255), 1) else: cv2.rectangle(img2, (v[0], v[1]), (v[2], v[3]), (255,0,0), 1) cv2.putText(img2, "{:.2f}".format(detects[i, -1]), (v[0], v[1]+9), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,0,255), 1) for g in GT: cv2.rectangle(img2, (g[0], g[1]), (g[2], g[3]), (0,255,0), 1) cv2.imwrite("out.jpg", img2) cv2.imshow("result", img2) cv2.waitKey(0)
code_generation
299
MIT
gasyori_100_knocks
pythonを用いて、物体検出の評価指標を実装しなさい。 検出はBounding-boxとそのクラスの2つが一致していないと、精度の評価ができない。 検出の評価指標には、Recall, Precision, F-score, mAPなどが存在する。 ### Recall ... 正解の矩形がどれだけ検出できたか。正解をどれだけ網羅できたかを示す。[0,1]の範囲を取り、1が最高。 G' ... Ground-truthの中で検出のどれかとIoUが閾値t以上となったGround-truthの数。 G ... Ground-truthの矩形の数。 Recall = G' / G ### Precision ... 検出がどれだけ正確に行われたかを示す。[0,1]の範囲を取り、1が最高。 D' ... 検出の中で、Ground-truthのどれかとIoUが閾値t以上となった検出の数。 D ... 検出の数。 Precision = D' / D ### F-score ... RecallとPrecisonの調和平均。 2つのバランスを示すもので、[0,1]の範囲を取り、1が最高。 F-score = 2 * Recall * Precision / (Recall + Precision) 文字を検出する文字検出はRecall, Precision, F-scoreで精度を測ることが多い。 ### mAP ... Mean Average Precision。物体を検出する物体検出では、mAPで測ることが多い。mAPの計算方法は少し複雑である。 1. 各検出に関してGround-truthとのIoUが閾値t以上かどうかを判断して、表を作成する。 Detect | judge ------------------ detect1 | 1 (1はGround-truthとのIoU>=tとなったもの) detect2 | 0 (0はGround-truthとのIoU<tとなったもの) detect3 | 1 2. mAP = 0として、上から順に見て、judgeが1の時は、見ているものの上すべてに関して、Precisionを計算し、mAPに加算する。 3. 上から順に2を行い、全て行ったら、加算回数でmAPを割る。 以上でmAPが求まる。上の例でいうと、 1. detect1 が1なので、Precisionを求める。Precision = 1/1 = 1なので、mAP = 1 2. detect2 が0なので、無視。 3. detect3 が1なので、Precisionを求める。Precision = 2/3 = 0.67 なので、 mAP = 1 + 0.67 = 1.67 4. mAPに加算したのは計2回なので、mAP = 1.67 / 2 = 0.835 となる。 ここでは、閾値t=0.5として、Recall, Precision, F-score, mAPを算出せよ。 Ground-truthは次とする。 # [x1, y1, x2, y2] GT = np.array(((27, 48, 95, 110), (101, 75, 171, 138)), dtype=np.float32) ここでは、GTとのIoUが0.5以上の検出を赤、それ以外を青にして描画せよ。