minAreaRect internal Error

asked 2018-10-15 11:14:58 -0500

agbj gravatar image

I am trying to run the following code but an error arise when I call the minAreaRect but it goes well through boundingRect. I am confused because these two functions take the same input. The image is in this link: img

#!/usr/bin/env python

import numpy as np
import cv2

img = cv2.imread('test.png', cv2.IMREAD_COLOR)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# define range of blue color in HSV
gimp_lower_blue = np.array([210, 60, 60])
gimp_upper_blue = np.array([230, 80, 80])

# https://stackoverflow.com/questions/10948589/choosing-the-correct-upper-and-lower-hsv-boundaries-for-color-detection-withcv
gimp_to_opencv_hsv = np.array([180.0/360, 255.0/100, 255.0/100])
lower_blue = np.multiply(gimp_lower_blue, gimp_to_opencv_hsv)
upper_blue = np.multiply(gimp_upper_blue, gimp_to_opencv_hsv)

# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)
contours = cv2.findContours(
    mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
x, y, w, h = cv2.boundingRect(contours[0])
cv2.rectangle(img, (x-3, y-3), (x+w+3, y+h+3), (0, 255, 0), 5)
cv2.imshow('image', img)
cv2.waitKey()

rect = cv2.minAreaRect(contours[0])
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
cv2.imshow('image', img)
cv2.waitKey(0)

The first line of the error is: OpenCV Error: Assertion failed (total >= 0 && (depth == CV_32F || depth == CV_32S)) in convexHull, file /build/opencv-L2vuMj/opencv-3.2.0+dfsg/modules/imgproc/src/convhull.cpp, line 136

edit retag flag offensive close merge delete

Comments

findContours returns a tuple of (image, contours,hierarchy), so contours[0] is NOT a contour, and even contours[1] would be a LIST of contours.

berak gravatar imageberak ( 2018-10-15 11:24:45 -0500 )edit

also, please update your cv2, 3.2 is several years old, and folks won't remember how things were, way back then.

berak gravatar imageberak ( 2018-10-15 11:26:39 -0500 )edit

I am using ROS that comes with opencv 3.2 bundled. My error was that i was expecting contours as the first argument and not the triple. That solves the problem. Thank you

agbj gravatar imageagbj ( 2018-10-25 11:21:52 -0500 )edit