Skip to content

UnboundLocalError: local variable 'x' referenced before assignment #88

Open
@nadhirhasan

Description

Hi, there is problem is findContour function. when draw=False it throw error due to the variable unassigned, basically we have to put
cv2.boundingRect(approx) above the drawCon condition.

def findContours(img, imgPre, minArea=1000, maxArea=float('inf'), sort=True,
                 filter=None, drawCon=True, c=(255, 0, 0), ct=(255, 0, 255),
                 retrType=cv2.RETR_EXTERNAL, approxType=cv2.CHAIN_APPROX_NONE):
    """
    Finds Contours in an image.
    Sorts them based on area
    Can use filtration to get based on x corner points
    e.g. filter = [3,4] will return triangles and rectangles both

    :param img: Image on which we want to draw.
    :param imgPre: Image on which we want to find contours.
    :param minArea: Minimum Area to detect as valid contour.
    :param maxArea: Maximum Area to detect as valid contour.
    :param sort: True will sort the contours by area (biggest first).
    :param filter: List of filters based on the corner points e.g. [3, 4, 5].
                   If None, no filtering will be done.
    :param drawCon: Draw contours boolean.
    :param c: Color to draw the contours.
    :param ct: Color for Text
    :param retrType: Retrieval type for cv2.findContours (default is cv2.RETR_EXTERNAL).
    :param approxType: Approximation type for cv2.findContours (default is cv2.CHAIN_APPROX_NONE).

    :return: Found contours with [contours, Area, BoundingBox, Center].
    """
    conFound = []
    imgContours = img.copy()
    contours, hierarchy = cv2.findContours(imgPre, retrType, approxType)

    for cnt in contours:
        area = cv2.contourArea(cnt)
        if minArea < area < maxArea:
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)

            if filter is None or len(approx) in filter:
                x, y, w, h = cv2.boundingRect(approx)  #### Change
                if drawCon:
                    #### x, y, w, h = cv2.boundingRect(approx)
                    cv2.drawContours(imgContours, cnt, -1, c, 3)
                    cv2.putText(imgContours, str(len(approx)), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, ct, 2)
                cx, cy = x + (w // 2), y + (h // 2)
                cv2.rectangle(imgContours, (x, y), (x + w, y + h), c, 2)
                cv2.circle(imgContours, (x + (w // 2), y + (h // 2)), 5, c, cv2.FILLED)
                conFound.append({"cnt": cnt, "area": area, "bbox": [x, y, w, h], "center": [cx, cy]})

    if sort:
        conFound = sorted(conFound, key=lambda x: x["area"], reverse=True)

    return imgContours, conFound
    ```

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions