Python imutils.is_cv2() Examples

The following are 7 code examples of imutils.is_cv2(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module imutils , or try the search function .
Example #1
Source File: main.py    From Traffic-Sign-Detection with MIT License 5 votes vote down vote up
def findContour(image):
    #find contours in the thresholded image
    cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE    )
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]
    return cnts 
Example #2
Source File: rgbhist.py    From photomosaic with MIT License 5 votes vote down vote up
def describe(self, image):
		hist = cv2.calcHist([image], [0, 1, 2],
			None, self.bins, [0, 256, 0, 256, 0, 256])
 
		if imutils.is_cv2():
			hist = cv2.normalize(hist)
 
		else:
			hist = cv2.normalize(hist,hist)
 
		return hist.flatten() 
Example #3
Source File: __init__.py    From pylgbst with MIT License 5 votes vote down vote up
def _find_color(self):
        # from https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/
        # and https://thecodacus.com/opencv-object-tracking-colour-detection-python/#.W2DHFd_IQsM

        blurred = cv2.GaussianBlur(self.cur_img, (11, 11), 0)
        hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)

        try:
            # having color values in file allows finding values easier
            with open(os.path.join(os.path.dirname(__file__), "color.json")) as fhd:
                data = json.loads(fhd.read())
                lower = tuple(data[0])
                upper = tuple(data[1])
        except BaseException:
            logging.debug("%s", traceback.format_exc())
            lower = (100, 100, 100,)
            upper = (130, 255, 255,)
        mask = cv2.inRange(hsv, lower, upper)
        mask = cv2.erode(mask, None, iterations=5)
        mask = cv2.dilate(mask, None, iterations=5)

        # if not (int(time.time()) % 2):
        #    self.cur_img = mask

        ret, thresh = cv2.threshold(mask, 20, 255, 0)
        cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        cnts = cnts[0] if imutils.is_cv2() else cnts[1]

        return self._reduce([cv2.boundingRect(c) for c in cnts]) 
Example #4
Source File: distance_to_camera.py    From Hand-Detection-and-Distance-Estimation with MIT License 5 votes vote down vote up
def find_marker(image):
    # convert the image to grayscale, blur it, and detect edges
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    edged = cv2.Canny(gray, 35, 125)

    # find the contours in the edged image and keep the largest one;
    # we'll assume that this is our piece of paper in the image
    cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]
    c = max(cnts, key = cv2.contourArea)

    # compute the bounding box of the of the paper region and return it
    return cv2.minAreaRect(c) 
Example #5
Source File: motion_detector.py    From study-picamera-examples with MIT License 4 votes vote down vote up
def process_image(self, frame):
        frame = imutils.resize(frame, width=min(500, frame.shape[1]))
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (21, 21), 0)

        if self.avg is None:
            print('Starting background model...')
            self.avg = gray.copy().astype('float')
            return frame

        cv2.accumulateWeighted(gray, self.avg, 0.5)
        frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(self.avg))
        thresh = cv2.threshold(frameDelta, 5, 255, cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)

        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if imutils.is_cv2() else cnts[1]

        for c in cnts:
            if cv2.contourArea(c) < 5000:
                continue

            (x, y, w, h) = cv2.boundingRect(c)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        
        return frame 
Example #6
Source File: rpis_camera.py    From rpi-security with GNU General Public License v2.0 4 votes vote down vote up
def handle_new_frame(self, frame, past_frame):
        (h, w) = frame.shape[:2]
        r = 500 / float(w)
        dim = (500, int(h * r))
        frame = cv2.resize(frame, dim, cv2.INTER_AREA) # We resize the frame
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # We apply a black & white filter
        gray = cv2.GaussianBlur(gray, (21, 21), 0) # Then we blur the picture

        # if the first frame is None, initialize it because there is no frame for comparing the current one with a previous one
        if past_frame is None:
            past_frame = gray
            return past_frame

        # check if past_frame and current have the same sizes
        (h_past_frame, w_past_frame) = past_frame.shape[:2]
        (h_current_frame, w_current_frame) = gray.shape[:2]
        if h_past_frame != h_current_frame or w_past_frame != w_current_frame: # This shouldnt occur but this is error handling
            logger.error('Past frame and current frame do not have the same sizes {0} {1} {2} {3}'.format(h_past_frame, w_past_frame, h_current_frame, w_current_frame))
            return

        # Detect when too dark to reduce false alarms
        if self.camera.digital_gain == Fraction(187/128) and self.camera.analog_gain == Fraction(8):
            if not self.too_dark_message_printed:
                logger.info("Too dark to run motion detection")
                self.too_dark_message_printed = True
            return None
        else:
            self.too_dark_message_printed = False

        # compute the absolute difference between the current frame and first frame
        frame_delta = cv2.absdiff(past_frame, gray)
        # then apply a threshold to remove camera motion and other false positives (like light changes)
        thresh = cv2.threshold(frame_delta, 50, 255, cv2.THRESH_BINARY)[1]

        # dilate the thresholded image to fill in holes, then find contours on thresholded image
        thresh = cv2.dilate(thresh, None, iterations=2)
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if imutils.is_cv2() else cnts[1]

        # loop over the contours
        for c in cnts:
            # if the contour is too small, ignore it
            countour_area = cv2.contourArea(c)

            if countour_area < self.motion_detection_threshold:
                continue

            logger.info("Motion detected! Motion level is {0}, threshold is {1}".format(countour_area, self.motion_detection_threshold))
            # Motion detected because there is a contour that is larger than the specified self.motion_detection_threshold
            # compute the bounding box for the contour, draw it on the frame,
            (x, y, w, h) = cv2.boundingRect(c)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            self.handle_motion_detected(frame)

        return None 
Example #7
Source File: mainDetect.py    From DE3-ROB1-CHESS with Creative Commons Attribution 4.0 International 4 votes vote down vote up
def detectSquareChange(self, previous, current, debug=True):
        """
        Take a previous and a current image and returns the squares where a change happened, i.e. a figure has been
        moved from or to.
        """

        debugImg = current.copy()

        # Convert the images to grayscale
        grayA = cv2.cvtColor(previous, cv2.COLOR_BGR2GRAY)
        grayB = cv2.cvtColor(current, cv2.COLOR_BGR2GRAY)

        # Computes the Structural Similarity Index (SSIM) between previous and current
        (score, diff) = compare_ssim(grayA, grayB, full=True)
        diff = (diff * 255).astype("uint8")

        ## DEBUG
        # print("SSIM: {}".format(score))

        # Threshold the difference image, followed by finding contours to obtain the regions of the two input images that differ
        thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if imutils.is_cv2() else cnts[1]

        # Loop over the contours to return centres of differences
        centres = []

        for c in cnts:
            # Compute the bounding box and find its centre
            try:
                # Area
                area = cv2.contourArea(c)
                if area > 100:
                    (x, y, w, h) = cv2.boundingRect(c)
                    centre = (int(x + w / 2), int(y + h / 2))
                    centres.append(centre)
                    cv2.circle(debugImg, centre, 3, 255, 2)
                    cv2.rectangle(debugImg, (x, y), (x + w, y + h), (0, 0, 255), 2)
            except:
                pass

        ## DEBUG
        if debug:
            cv2.imshow("Detected Move", debugImg)

        return centres