search
HomeBackend DevelopmentPython TutorialHow to get the boundary vertices of image chunking using Python and OpenCV?

Efficiently extract image chunking boundary vertices using Python and OpenCV

In image processing, it is often necessary to segment the image into blocks and extract the boundary vertices of each block. Suppose there is a single channel image, and after processing, it forms a mesh of h×m, and the value of each mesh block is incremented from 1. This article will explain how to use Python and OpenCV libraries to efficiently find the boundary vertices of each block.

How to get the boundary vertices of image chunking using Python and OpenCV?

Methods and code examples

We will use OpenCV to read the image and perform chunking processing (assuming the chunked image already exists, stored in a two-dimensional NumPy array, each element represents the label of the chunk). Then, use the power of NumPy to find the boundary vertices of each block.

The following code demonstrates how to traverse each block, find its boundary pixel point and record its coordinates:

 import cv2
import numpy as np

# Sample chunked image (replace with your actual chunked image data)
segmented_image = np.array([
    [1, 1, 1, 2, 2],
    [1, 1, 1, 2, 2],
    [3, 3, 3, 2, 2],
    [3, 3, 3, 4, 4],
    [3, 3, 3, 4, 4]
])

# Dictionary block_boundaries = {}

# traverse each block label for label in np.unique(segmented_image):
    # Create a mask, keep only the current block mask = (segmented_image == label).astype(np.uint8)

    # Use OpenCV to find contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Extract boundary vertices if contours:
        contour = contours[0]
        vertices = contour.reshape(-1, 2)
        block_boundaries[label] = vertices

# Print the boundary vertices of each block for label, vertices in block_boundaries.items():
    print(f"Border vertex coordinates of block {label}:")
    print(vertices)

This code uses OpenCV's findContours function to efficiently find the outer contour of each block, and then extract the vertex coordinates on the contour. The block_boundaries dictionary stores the mapping relationship between each block label and its corresponding boundary vertex coordinates.

Improvements and extensions

This method is suitable for simple rectangular block segmentation. For more complex shapes, more advanced image processing techniques may be required, such as segmentation methods based on region growth or more complex contour analysis algorithms. In addition, the code can be modified according to actual needs, such as adding error handling or optimizing performance. If there are more specific needs or questions, further requests are welcome.

The above is the detailed content of How to get the boundary vertices of image chunking using Python and OpenCV?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool