1
0

OpenCVで検出した画像の輪郭をCSVで出力

Last updated at Posted at 2024-08-25

概要

そのまんまですがOpenCVで検出した画像の輪郭をCSVで出力するコードです。

環境

  • Ubuntu 24.04.LTS
  • Python 3.12.3 (venvで仮想環境化して使用)

pipのリスト()

contourpy==1.2.1
cycler==0.12.1
fonttools==4.53.1
kiwisolver==1.4.5
matplotlib==3.9.2
numpy==2.1.0
opencv-python==4.10.0.84
packaging==24.1
pillow==10.4.0
pyparsing==3.1.3
python-dateutil==2.9.0.post0
six==1.16.0

参考URL

ソースコード

puts 'import cv2'
import matplotlib.pyplot as plt
import numpy as np
np.set_printoptions(threshold=np.inf)

# 画像の読み込み
img = cv2.imread('test.png')

# HSV変換
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV_FULL)

#色相、彩度、明度の画像に分離
img_h, img_s, img_v = cv2.split(img_hsv)

ret, thresh = cv2.threshold(img_v, 150, 255, cv2.THRESH_BINARY)

contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0]

# 面積が一定以上の輪郭のみ残す。
area_thresh = 200
contours = list(filter(lambda x: cv2.contourArea(x) > area_thresh, contours))

# 輪郭を画像に書き込む
output = cv2.drawContours(img, contours, -1, (0,255,0), 1)

contours_str = str(contours)

# 出力したい文字列からいらない文字を削除 
# 雑なので何かいい方法あったら教えてください
contours_str = contours_str.replace('array(', '')
contours_str = contours_str.replace('dtype=int32)', "")
contours_str = contours_str.replace('[', '')
contours_str = contours_str.replace(']', '')
contours_str = contours_str.replace(' ', '')
contours_str = contours_str.replace(',\n', '')

with open('result.csv', 'w') as f:
   f.writelines(contours_str)
    
#画像の出力
cv2.imwrite('result.png',output)

実行結果

いつか出すかも

所感

Yoloを使って分けたボックスに対してOpenCVの輪郭抽出を使うと綺麗に出来るんじゃない?
と思ったり

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0