import cv2
# 画像の読み込み
image = cv2.imread('source.png')
# グレースケール化
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 二値化
image = cv2.threshold(image, 254, 255, cv2.THRESH_BINARY)[1]
# 明度反転
image = cv2.bitwise_not(image)
# 画像の保存
cv2.imwrite('1.png', image)
1
import cv2
# 細線化した画像を返す関数
def getThinnedImage(image):
return cv2.ximgproc.thinning(image)
# 画像の読み込み
image = cv2.imread('1.png')
# グレースケール化
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 二値化
image = cv2.threshold(image, 254, 255, cv2.THRESH_BINARY)[1]
# 細線化
image = getThinnedImage(image)
# 画像の保存
cv2.imwrite('2.png', image)
2
import cv2
import numpy as np
# 細線化した画像を返す関数
def getThinnedImage(image):
return cv2.ximgproc.thinning(image)
# 画像の読み込み
image = cv2.imread('1.png')
# グレースケール化
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 二値化
image = cv2.threshold(image, 254, 255, cv2.THRESH_BINARY)[1]
# 画像のサイズ
height, width = image.shape[:2]
# 全ピクセル数の1%のノイズを追加
for i in range(int(height * width * 0.01)):
x = np.random.randint(0, width)
y = np.random.randint(0, height)
# x, y座標のピクセルの明度を反転
image[y, x] = 255 - image[y, x]
# 画像の保存
cv2.imwrite('3_1.png', image)
# 細線化
image = getThinnedImage(image)
# 画像の保存
cv2.imwrite('3_2.png', image)
3_1

3_2
import cv2
import numpy as np
# 細線化した画像を返す関数
def getThinnedImage(image):
return cv2.ximgproc.thinning(image)
# 膨張処理した画像を返す
def dilate_image(image):
kernel = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], np.uint8)
dilated_image = cv2.dilate(image, kernel, iterations=1)
return dilated_image
# 収縮処理した画像を返す
def erode_image(image):
# 画像を白黒反転させる
image = cv2.bitwise_not(image)
# 膨張処理
image = dilate_image(image)
# 画像を白黒反転させる
image = cv2.bitwise_not(image)
return image
# 画像の読み込み
image = cv2.imread('3_1.png')
# グレースケール化
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 二値化
image = cv2.threshold(image, 254, 255, cv2.THRESH_BINARY)[1]
# 膨張→収縮→収縮の処理を加える
image = dilate_image(image)
image = erode_image(image)
image = erode_image(image)
# 画像の保存
cv2.imwrite('4_1.png', image)
# 細線化
image = getThinnedImage(image)
# 画像の保存
cv2.imwrite('4_2.png', image)
4_1

4_2