Created
December 12, 2021 04:32
-
-
Save ksasao/9429a83c3f81bdf5a3e51de0c40a7477 to your computer and use it in GitHub Desktop.
ZOZOSUIT2のマーカーを読み取るやつ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import random | |
import math | |
import cv2 | |
from PIL import Image | |
import sys | |
def detect_markers(im): | |
markers = [] | |
height, width = im.shape[:2] | |
# 輪郭線抽出のための二値化 | |
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) | |
th = cv2.adaptiveThreshold(im_gray,255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV,121,40) | |
# 画像から輪郭線を抽出 | |
contours, hierarchy = cv2.findContours(th, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) | |
# 背景を黒に | |
im[:] = (0, 0, 0) | |
limit = 0.5 | |
for (i,cnt) in enumerate(contours): | |
# 楕円で近似する | |
if len(cnt)>=5: | |
(x,y),(h,w),deg = cv2.fitEllipse(cnt) | |
if x > 0 and x < width and y > 0 and y < height and w*h > 50 and w/h < 1/limit and w/h > limit and w < 200: | |
col = th[int(y),int(x)] | |
if th[int(y),int(x)] > 0: | |
con = hierarchy[0][i][2] | |
if con != -1: | |
markers.append([int(x),int(y),0]) | |
else: | |
markers.append([int(x),int(y),1]) | |
return markers | |
def draw_marker(im,pos,color): | |
x = int(pos[0]) | |
y = int(pos[1]) | |
(b,g,r) = color | |
cv2.line(im, (x - 3,y - 3),(x + 3, y + 3), (b,g,r), 2) | |
cv2.line(im, (x + 3,y - 3),(x - 3, y + 3), (b,g,r), 2) | |
if __name__ == '__main__': | |
args = sys.argv | |
input_file_name = args[1] | |
output_file_name = args[1] + ".png" | |
frame = cv2.imread(input_file_name) | |
id_list = detect_markers(frame) | |
for id in id_list: | |
x,y,c = id | |
if c == 0: | |
draw_marker(frame, (x,y), (0,255,255)) | |
else: | |
draw_marker(frame, (x,y), (0,255,0)) | |
print(id) | |
cv2.imshow('window',frame) | |
cv2.imwrite(output_file_name, frame) | |
key = cv2.waitKey(3000) | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment