外接矩形、外接円

V3.0.0

In [15]:
# -*- coding: utf-8 -*-
import cv2
import numpy as np
#Ipythonで表示用の設定
import matplotlib.pyplot as plt
%matplotlib inline

#画像読込
in_img1 = cv2.imread("bird.tif") 
in_img2 = cv2.imread("bird.tif") 
in_img3 = cv2.imread("bird.tif") 

#グレイ画像へ変換
gray_img   = cv2.cvtColor(in_img1, cv2.COLOR_BGR2GRAY)
#2値化
ret,thresh = cv2.threshold(gray_img,220,1,0)
#輪郭抽出
image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

#外接矩形
cnt = contours[0]
x,y,w,h = cv2.boundingRect(cnt)
img = cv2.rectangle(in_img1,(x,y),(x+w,y+h),(0,255,0),2)

#外接矩形(回転を許す場合)
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
im = cv2.drawContours(in_img2,[box],0,(0,0,255),2)

#外接円
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
img = cv2.circle(in_img3,center,radius,(255,0,0),2)

#OpenCVがBGRなのでRGBに変換
disp_out_img1 = cv2.cvtColor(in_img1, cv2.COLOR_BGR2RGB)
disp_out_img2 = cv2.cvtColor(in_img2, cv2.COLOR_BGR2RGB)
disp_out_img3 = cv2.cvtColor(in_img3, cv2.COLOR_BGR2RGB)


#画像表示
plt.figure(figsize=(15,5))
plt.subplot(131)
plt.imshow(disp_out_img1)
plt.subplot(132)
plt.imshow(disp_out_img2)
plt.subplot(133)
plt.imshow(disp_out_img3)
Out[15]:
<matplotlib.image.AxesImage at 0xac4a210>
inserted by FC2 system