OpenCV-PythonはROI(長方形とポリゴン)を選択します



Opencv Python Selects Roi Rectangle



長方形のROI

OpenCVには、ROIとして長方形の領域を直接選択するAPIが付属しています。 APIは、ターゲット追跡モジュール、主にcv2.selectROI()関数にあります。

import cv2 import imutils img = cv2.imread('./test_image.jpg') img = imutils.resize(img, ) roi = cv2.selectROI(windowName='roi', img=img, showCrosshair=True, fromCenter=False) x, y, w, h = roi cv2.rectangle(img=img, pt1=(x, y), pt2=(x + w, y + h), color=(0, 0, 255), thickness=2) cv2.imshow('roi', img) cv2.waitKey(0) cv2.destroyAllWindows()



2.ポリゴンのROI

主にマウスの相互作用によって描画されるポリゴンROI:

1.左ボタンをクリックして、ポリゴンのポイントを選択します



2.右クリックして、最後に選択したポイントを削除します

3.中央のボタンをクリックして、ROI領域を特定し、視覚化します。

4.「S」キーを押して、ポリゴンROI領域のポイントをローカルの「config.pkl」ファイルに保存します。



import cv2 import imutils import numpy as np import joblib Pts = [] # for storing points # :mouse callback function def draw_roi(event, x, y, flags, param): img2 = img.copy() If event == cv2.EVENT_LBUTTONDOWN: # Left click, select point pts.append((x, y)) If event == cv2.EVENT_RBUTTONDOWN: # Right click to cancel the last selected point pts.pop() If event == cv2.EVENT_MBUTTONDOWN: # mask = np.zeros(img.shape, np.uint8) points = np.array(pts, np.int32) points = points.reshape((-1, 1, 2)) # mask = cv2.polylines(mask, [points], True, (255, 255, 255), 2) Mask2 = cv2.fillPoly(mask.copy(), [points], (255, 255, 255)) # for ROI Mask3 = cv2.fillPoly(mask.copy(), [points], (0, 255, 0)) # for displaying images on the desktop show_image = cv2.addWeighted(src1=img, alpha=0.8, src2=mask3, beta=0.2, gamma=0) cv2.imshow('mask', mask2) cv2.imshow('show_img', show_image) ROI = cv2.bitwise_and(mask2, img) cv2.imshow('ROI', ROI) cv2.waitKey(0) if len(pts) > 0: # Draw the last point in pts cv2.circle(img2, pts[-1], 3, (0, 0, 255), -1) if len(pts) > 1: # for i in range(len(pts) - 1): Cv2.circle(img2, pts[i], 5, (0, 0, 255), -1) # x ,y is the coordinates of the mouse click place cv2.line(img=img2, pt1=pts[i], pt2=pts[i + 1], color=(255, 0, 0), thickness=2) cv2.imshow('image', img2) #Create images and windows and bind windows to callback functions img = cv2.imread('./test_image.jpg') img = imutils.resize(img, ) cv2.namedWindow('image') cv2.setMouseCallback('image', draw_roi) Print('[INFO] Click the left button: select the point, right click: delete the last selected point, click the middle button: determine the ROI area') Print('[INFO] Press ‘S’ to determine the selection area and save it) Print('[INFO] Press ESC to quit') while True: key = cv2.waitKey(1) & 0xFF if key == 27: break if key == ord('s'): saved_data = { 'ROI': pts } joblib.dump(value=saved_data, filename='config.pkl') Print('[INFO] ROI coordinates have been saved to local.') break cv2.destroyAllWindows()