LoginSignup
6
1

More than 3 years have passed since last update.

[OpenCV] マウスクリックで画像からROIを切り取る [2]

Last updated at Posted at 2021-02-08

はじめに

OpenCVを利用して、マウスクリックイベントを練習してみました。

やりたいこと

マウスでBounding Boxを描き、その領域を切り取りたいと思います。
image.png

やり方の説明

OpenCVのcv2.selectROI()を使います。
Raw Image(img_raw)に対し、下記の命令を実行すると、Bounding Boxの座標がROI変数に格納されます。

ROI = cv2.selectROI('Select ROIs', img_raw, fromCenter = False, showCrosshair = False)

print('ROI',ROI)

結果
ROI (115, 99, 275, 336)

image.png

ROIに格納された座標を利用して、Raw ImageからCropします。

x1 = ROI[0]
y1 = ROI[1]
x2 = ROI[2]
y2 = ROI[3]

#Crop Image
img_crop = img_raw[int(y1):int(y1+y2),int(x1):int(x1+x2)]

実行結果

ROI_bounding_box.gif

コード

import cv2
import numpy as np

img_raw = cv2.imread('./images/lena.png')

#select ROIs function
ROI = cv2.selectROI('Select ROIs', img_raw, fromCenter = False, showCrosshair = False)


x1 = ROI[0]
y1 = ROI[1]
x2 = ROI[2]
y2 = ROI[3]

print('ROI', ROI)

#Crop Image
img_crop = img_raw[int(y1):int(y1+y2),int(x1):int(x1+x2)]

cv2.imshow("crop", img_crop)

cv2.waitKey(0)


参考資料

  1. [OpenCV] マウスクリックで画像からROIを切り取る [1]
  2. Multiple ROISを得る方法はこちらのリンクをご参照ください。
  3. How to select a bounding box ( ROI ) in OpenCV (C++/Python) ?
6
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
6
1