色と色との間に黒で輪郭をつけそれを元にopenCVで輪郭取得を
したいとおもっております.
「輪郭をつける」の意味がよくわかりませんが、輪郭を画像から抽出したいということでしょうか?
輪郭抽出
python
1import cv2
2import numpy as np
3
4# 画像を読み込む。
5img = cv2.imread('test.png', cv2.IMREAD_GRAYSCALE)
6
7# 2値化
8thresh, binary = cv2.threshold(
9 img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
10
11# closing でノイズを消す
12kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
13binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel, iterations=2)
14
15# 輪郭抽出する。(OpenCV 3)
16_, contours, hierarchy = cv2.findContours(
17 binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
18
19# OpenCV4 の場合
20#contours, hierarchy = cv2.findContours(
21# binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
結果描画
python
1import matplotlib.pyplot as plt
2from matplotlib.patches import Polygon
3
4def draw_contours(ax, img, contours):
5 ax.imshow(img, cmap='gray')
6 ax.axis('off')
7 for i, cnt in enumerate(contours):
8 cnt = np.squeeze(cnt, axis=1) # (NumPoints, 1, 2) -> (NumPoints, 2)
9 # 輪郭の点同士を結ぶ線を描画する。
10 ax.add_patch(Polygon(cnt, color='b', fill=None, lw=2))
11 # 輪郭の点を描画する。
12 ax.plot(cnt[:, 0], cnt[:, 1], 'ro', mew=0, ms=4)
13 # 輪郭の番号を描画する。
14 ax.text(cnt[0][0], cnt[0][1], i, color='orange', size='20')
15
16fig, ax = plt.subplots(figsize=(6, 6))
17draw_contours(ax, img, contours)
18plt.show()
抽出した輪郭を可視化