import cv2
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
filename = input()
img = cv2.imread(filename)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
contours, hierarchy = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
def draw_contours(ax, img, contours):
ax.imshow(img)
ax.set_axis_off()
for i, cnt in enumerate(contours):
# 形状を変更する。(NumPoints, 1, 2) -> (NumPoints, 2)
cnt = cnt.squeeze(axis=1)
# 輪郭の点同士を結ぶ線を描画する。
# ax.add_patch(Polygon(cnt, color="b", fill=None, lw=1))
# 輪郭の点を描画する。
# ax.plot(cnt[:, 0], cnt[:, 1], "ro", mew=0, ms=2)
# 輪郭の番号を描画する。
ax.text(cnt[0][0], cnt[0][1]-15, i+1, color="orange", size="20")
fig, ax = plt.subplots()
draw_contours(ax, img, contours)
plt.savefig('result.png')
print(len(contours))
plt.show()
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme