Skip to content

Instantly share code, notes, and snippets.

@siphomateke
Last active May 21, 2019 17:41
Show Gist options
  • Save siphomateke/78cc10a5c0a978f9399098e92754c1ce to your computer and use it in GitHub Desktop.
Save siphomateke/78cc10a5c0a978f9399098e92754c1ce to your computer and use it in GitHub Desktop.
Example OpenCV Python code on how to extract sub images defined by rectangles of a particular color in an image
import numpy as np
import cv2
# The hsv color of the rectangle (0, 255, 255)
# If the hsv color will not be exactly pure you can change lower and upper accordingly
lower = np.array([0, 255, 255], np.uint8)
upper = np.array([0, 255, 255], np.uint8)
img = cv2.imread("img.png", cv2.IMREAD_COLOR)
# if image was loaded correctly
if img is not None:
# convert to hsv
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Extract the hue value
hue = img_hsv[:, :, 0]
# Threshold to extract only color we want
thresh = cv2.inRange(img_hsv, lower, upper)
# Detect contours with tree hierachy
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# For each contour extract the child idxs
# This is so that the inside of the rectangle is extracted
# otherwise we would get the rectangle in our extracted images
idxs = []
for i in xrange(len(contours)):
# more info on contour hierachy: http://docs.opencv.org/trunk/d9/d8b/tutorial_py_contours_hierarchy.html
child = hierarchy[0][i][2]
if child > 0:
idxs.append(child)
# convert to numpy array and get only child contours
contours = np.array(contours)
contours = contours[idxs]
# get the bounding rectangles for each contour
rects = [cv2.boundingRect(c) for c in contours]
# add some inwards padding to the ROI to allow for error
padding = 2
extracted_imgs = []
for r in rects:
x = r[0]+padding
y = r[1]+padding
w = r[2]-(padding*2)
h = r[3]-(padding*2)
roi = img[y:y+h, x:x+w]
extracted_imgs.append(roi)
# Display the extracted images
for i in xrange(len(extracted_imgs)):
img = extracted_imgs[i]
cv2.imshow("Image {}".format(i),img)
cv2.waitKey(0)
@Jibin-John
Copy link

No output but no compilation errors

@siphomateke
Copy link
Author

@Jibin-John Sorry for not replying sooner. Did you figure it out?

If you didn't, make sure you changed the image path to point to your image on line 9. I wrote this rather quickly as an example so it doesn't throw errors if the image was not loaded correctly.

If it still doesn't work I'm afraid I can't help - I haven't worked with OpenCV in a while.

Copy link

ghost commented Aug 24, 2018

Same.. no error but no output too..
can you please help

@siphomateke
Copy link
Author

@aroragaurav14 I'm afraid I can't help. I just tested it and it still works perfectly on my end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment