Codementor Events

Extract a particular object from images using OpenCV in Python ?

Published May 11, 2018Last updated Jul 08, 2019
Extract a particular object from images using OpenCV in Python ?

Extracting a particular object from image using OpenCV can be done very easily. We can write a program which allows us to select our desire portion in an image and extract that selected portion as well. Let’s do the code -

Task

  • draw shape on any image
  • re select the extract portion if necessary
  • extract particular object from the image

Code

Get the code from here or simply follow the code given below -

Open a text editor , write following piece of code -

# Capture the mouse click events in Python and OpenCV
'''
-> draw shape on any image 
-> reset shape on selection
-> crop the selection
run the code : python capture_events.py --image image_example.jpg
'''


# import the necessary packages
import argparse
import cv2

# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
ref_point = []
cropping = False

def shape_selection(event, x, y, flags, param):
  # grab references to the global variables
  global ref_point, cropping

  # if the left mouse button was clicked, record the starting
  # (x, y) coordinates and indicate that cropping is being
  # performed
  if event == cv2.EVENT_LBUTTONDOWN:
    ref_point = [(x, y)]
    cropping = True

  # check to see if the left mouse button was released
  elif event == cv2.EVENT_LBUTTONUP:
    # record the ending (x, y) coordinates and indicate that
    # the cropping operation is finished
    ref_point.append((x, y))
    cropping = False

    # draw a rectangle around the region of interest
    cv2.rectangle(image, ref_point[0], ref_point[1], (0, 255, 0), 2)
    cv2.imshow("image", image)

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())

# load the image, clone it, and setup the mouse callback function
image = cv2.imread(args["image"])
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", shape_selection)

# keep looping until the 'q' key is pressed
while True:
  # display the image and wait for a keypress
  cv2.imshow("image", image)
  key = cv2.waitKey(1) & 0xFF

  # if the 'r' key is pressed, reset the cropping region
  if key == ord("r"):
    image = clone.copy()

  # if the 'c' key is pressed, break from the loop
  elif key == ord("c"):
    break

# if there are two reference points, then crop the region of interest
# from teh image and display it
if len(ref_point) == 2:
  crop_img = clone[ref_point[0][1]:ref_point[1][1], ref_point[0][0]:ref_point[1][0]]
  cv2.imshow("crop_img", crop_img)
  cv2.waitKey(0)

# close all open windows
cv2.destroyAllWindows()

Run

ave the file as capture_events.py and for testing we selected a demo picture which located at the same directory. Now run the code by following -

python capture_events.py --image demo.jpg

Expected Output

First select the desire portion from the image. In addition , we can remove bad selection by pressing ‘r’ as programmed for making a new proper selection.


Fig: Make a selection

Now after selecting a proper selection like above , just press ‘c’ to extract, as programmed. It will appear like below -


Fig: Extracted portion

That’s it. This how we can extract a particular object from images using OpenCV and Python. You welcome to visist for more cool stuff.

Regards
World of Void.

.
.

Get in touch with Me:

Discover and read more posts from Mohammed Innat
get started
post commentsBe the first to share your opinion
ai232
4 years ago

Hi! I use an image .PNG but it doesn’t appear complete. Please, can you help me?

C
5 years ago

Hi. I saved that code in a file. Now I’m writing another file where I plan to use that function for my image called rotated.png. How do I call that file capture_events.py and make use of its function to extract an object from my ‘rotated’ image?

Mohammed Innat
5 years ago

Just import the capture_events file to another.

Show more replies