
まくまく
物体の外形に接する矩形を描き、その矩形の幅、高さ、面積などの情報を画像に表示してみようと思います。
使用するのはopenCV
使用するのは、画像処理ライブラリのopenCVです。ここではopenCVがインストールされているのを前提として書き進めていきます。
サンプルコード
import cv2
img = cv2.imread('test.jpg')
img_bit = cv2.bitwise_not(img)
img_gray = cv2.cvtColor(img_bit, cv2.COLOR_BGR2GRAY)
ret,img_th = cv2.threshold(img_gray,10,255,cv2.THRESH_BINARY)
img_con = img.copy()
contours, hierarchy = cv2.findContours(img_th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x, y, width, height = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
cv2.rectangle(img_con, (x, y), (x+width, y+height), (0, 255, 0), 1)
cv2.putText(img_con, "width"+str(int(width))+","+"height"+str(int(height)), (x, y), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255))
cv2.putText(img_con, "Rectangle Area"+str(int(width*height)), (x, y+20), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255))
cv2.putText(img_con, "Object Area"+str(int(area)), (x, y+40), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255))
cv2.imwrite('外接矩形.jpg',img_con)
元画像
この画像を用いて、輪郭検出します。
出力
コメント
上のプログラムで処理することで、外形に接する矩形を表示することができました。一部、ビルと家が一体化しているなどはありますが、描写自体は問題はないかと思います。
putTextで、矩形の幅と高さ、面積を表示させました。あと、contourAreaで取得した物体自体の面積も表示しています。