LoginSignup
2
1

More than 3 years have passed since last update.

OpenCVを使って画像の輪郭を抽出したい。

Last updated at Posted at 2021-01-31

画像の輪郭を抽出したい。

qiita.rb
import cv2
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
#画像を読み込み
im = cv2.imread('MRJ.jpg')
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
retval, im_bw = cv2.threshold(im_gray, 100, 255, cv2.THRESH_BINARY)

# 輪郭の検出
contours, hierarchy = cv2.findContours(im_bw, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

# 全ての輪郭を書き込んで出力
im_con = im.copy()
cv2.drawContours(im_con, contours, -1, (255,0,255), 2)
cv2.imwrite('result2.jpg', im_con)

im_result = Image.open("result2.jpg")

fig=plt.figure(figsize=(20,10))
#画像をarrayに変換
im_list = np.asarray(im_result)
#貼り付け
plt.imshow(im_list)
#表示
plt.show()

#im_result.show()

画像に輪郭線が書き込まれた画像

result2.jpg

画像を2値化したい。

qiita.rb
import cv2
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

im = cv2.imread('foot.jpg')
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
retval, im_bw = cv2.threshold(im_gray, 70, 255, cv2.THRESH_BINARY)
cv2.imwrite('foot_test.jpg', im_bw)
imshow(im_bw)

foot_test.jpg

2
1
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
2
1