English 中文(简体)
2. 如何大致上划入四点
原标题:How to approximate contour into four points

I have binary masks obtained from segmentation model, and I want to get four corners only of its contour that include majority of the points with minimal area as you can see in this image: enter image description here

The corners are not necessarily forming a rectangle, and the mask is noisy:

“entergraph

“在此处的影像描述”/</a

enter image description here

“在此处的影像描述”/</a

“entergraph

I have tried contour detection, approximation, and minAreaRect, but the rectangle is in many cases wider than the shape, and not minimal to the limit I want:

#!/usr/bin/env python3

import os
from os import path as osp
import cv2
import numpy as np

path = "seg_masks"
im_list = os.listdir(path)

def lcc(binary_image:np.ndarray)->np.ndarray:
    # Find connected components
    print(binary_image.shape, binary_image.dtype)
    num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image, connectivity=8)
    # Find the label (index) of the largest connected component
    largest_component_label = np.argmax(stats[1:, cv2.CC_STAT_AREA]) + 1  # Skip background label (0)
    largest_component_mask = (labels == largest_component_label).astype(np.uint8)
    largest_component_mask = largest_component_mask.astype(np.uint8)
    return largest_component_mask

for img_name in im_list:
    bgr_img_mask = cv2.imread(osp.join(path, img_name), 0)
    cv2.imwrite(osp.join(path, "white", img_name), bgr_img_mask)
    lcc_mask = lcc(bgr_img_mask)
    # Erosion to clean the mask contour a bit
    cl_ker = 5
    kernel = np.ones((cl_ker, cl_ker), np.uint8)
    erosion = cv2.erode(lcc_mask,kernel,iterations = 3)

    contours, _ = cv2.findContours(
        lcc_mask, mode=cv2.RETR_TREE, 
        method=cv2.CHAIN_APPROX_NONE
    )
    if(len(contours)):
        max_cnt = max(contours, key=cv2.contourArea)
        epsilon = 0.008 * cv2.arcLength(max_cnt, True)
        approx = cv2.approxPolyDP(max_cnt, epsilon, True)
        approx = np.squeeze(np.array(approx, dtype=int), axis=1)

        rect = cv2.minAreaRect(approx) 
        box = cv2.boxPoints(rect) 
        box = np.int0(box) 
        bgr_img_mask = cv2.drawContours(bgr_img_mask, [box], 0, 200, 2) 

        cv2.drawContours(bgr_img_mask, [approx], -1, 128, 2)
        bgr_img_mask = cv2.putText(bgr_img_mask, f"{round(epsilon,2)}", (50, 50) , 
                                   cv2.FONT_HERSHEY_SIMPLEX , 1, 255, 2, cv2.LINE_AA)
    win_name = "img"
    cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)
    cv2.imshow(win_name, bgr_img_mask)
    cv2.waitKey(0)

产出:

“entergraph

您能否指导我如何做到这一点? 感谢。

问题回答

(This answer is only "How to", without code. I hope this could be a bit help for you.)

Istarted minAreaRect result for max area range contour,maxing the 4-vertex status.

Objective function to minimize is defined as average distance from the contour edge along the square. This can be calculated with OpenCV s distanceTransform and LineIterator.

每个3个样本图像的结果:

“在此处的影像描述”/</a

“entergraph

“entergraph





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签