It is not clear in your question whether you really want to trim the information defined in the circuit, or to mask information that is not related to the selected circuit. I will find out what to do in both situations.
Information masking
Assuming you run cv2.findContours on your image, you get a structure that lists all the paths available on your image. I also assume that you know the outline index that was used to surround the object you want. Assuming this is stored in idx , first use cv2.drawContours to draw a filled version of this path on a blank image, and then use this image to index it to extract outside the object. This logic masks any irrelevant information and stores only what is important - what is defined in the circuit you choose. The code for this would look something like this, assuming your image is a grayscale image stored in img :
import numpy as np import cv2 img = cv2.imread('...', 0)
If you really want to crop ...
If you want to crop the image, you need to define the minimum bounding bounding rectangle of the area defined by the path. You can find the upper left and lower right angular of the bounding box, and then use indexing to cut what you need. The code will be the same as before, but there will be an additional trimming step:
import numpy as np import cv2 img = cv2.imread('...', 0)
The cropping code works so that when we define a mask to select the area defined by the path, we additionally find the smallest horizontal and vertical coordinates that define the upper left corner of the path. We also find the largest horizontal and vertical coordinates that define the bottom left angular contour. Then we use indexing with these coordinates to crop what we really need. Note that cropping a masked image is an image that erases everything except the information contained in the largest outline.
Note with OpenCV 3.x
It should be noted that the above code assumes that you are using OpenCV 2.4.x. Note that in OpenCV 3.x, the definition of cv2.drawContours has changed. In particular, the output is a three-element tuple in which the first image is the original and the other two parameters are the same as in OpenCV 2.4.x. So just change the cv2.findContours in the above code to ignore the first output:
_, contours, _ = cv2.findContours(...)
source share