概要
wslでpython-opencvやってみる。
輪郭を検出して、背景を消すをやって見た。
環境
windows10 64bit
インストール
sudo apt install Python3-opencv
元画像
結果
サンプルコード
import numpy as np
import cv2
img = cv2.imread("cat0.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 5, 70)
edges = cv2.dilate(edges, None)
edges = cv2.erode(edges, None)
h, w = img.shape[ : 2]
back = np.ones((h, w, 3), np.uint8) * 255
contour_info = []
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
for c in contours:
contour_info.append((c, cv2.isContourConvex(c), cv2.contourArea(c), ))
contour_info = sorted(contour_info, key = lambda c: c[2], reverse = True)
max_contour = contour_info[0]
mask = np.zeros(edges.shape)
cv2.fillConvexPoly(mask, max_contour[0], (255))
kernel = np.array([[0.0, -1.0, 0.0], [-1.0, 5.0, -1.0], [0.0, -1.0, 0.0]])
mask = cv2.filter2D(mask, -1, kernel)
res = np.where(np.expand_dims(mask < 1, -1), back, img)
cv2.imwrite('res14.png', res)
以上。