Last active
March 9, 2020 17:38
-
-
Save henrysue/38291720cdadb6bb26a16d9822b6ec66 to your computer and use it in GitHub Desktop.
Extract Bounding Box Coordinates from Image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
class ExtractImageWidget(object): | |
def __init__(self): | |
self.original_image = cv2.imread('test.png') | |
self.clone = self.original_image.copy() | |
cv2.namedWindow('image') | |
cv2.setMouseCallback('image', self.extract_coordinates) | |
# Bounding box reference points and boolean if we are extracting coordinates | |
self.image_coordinates = [] | |
self.extract = False | |
def extract_coordinates(self, event, x, y, flags, parameters): | |
# Record starting (x,y) coordinates on left mouse button click | |
if event == cv2.EVENT_LBUTTONDOWN: | |
self.image_coordinates = [(x,y)] | |
self.extract = True | |
# Record ending (x,y) coordintes on left mouse bottom release | |
elif event == cv2.EVENT_LBUTTONUP: | |
self.image_coordinates.append((x,y)) | |
self.extract = False | |
print('top left: {}, bottom right: {}'.format(self.image_coordinates[0], self.image_coordinates[1])) | |
print('x,y,w,h : ({}, {}, {}, {})'.format(self.image_coordinates[0][0], self.image_coordinates[0][1], self.image_coordinates[1][0] - self.image_coordinates[0][0], self.image_coordinates[1][1] - self.image_coordinates[0][1])) | |
# Draw rectangle around ROI | |
cv2.rectangle(self.clone, self.image_coordinates[0], self.image_coordinates[1], (0,255,0), 2) | |
cv2.imshow("image", self.clone) | |
pic = 1 | |
while pic = 1: | |
cv2.imshow('image', extract_image_widget.show_image()) | |
key = cv2.waitKey(0) | |
# Close program with keyboard 'q' | |
if key == ord('q'): | |
cv2.destroyAllWindows() | |
pic = 0 | |
exit() | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credits to @nathancy on Stack Overflow. Minor edits made for context, but major script author is still @nathancy
You can see his response to the question here.
Please check out his Stack Overflow profile here.