


How to optimize processing of high-resolution images in Python to find precise white circular areas?
Apr 01, 2025 pm 06:12 PMPython efficiently process high-resolution images and accurately locate white circular areas
This article explores how to efficiently process high-resolution images of 9000x7000 pixels using Python and OpenCV to accurately find two white circular areas. The original code has missed and misdetected problems. The following provides optimization solutions.
Problem description
Objective: Accurately locate two white circular areas in a high-resolution image. The existing code uses the Hough circle transformation, but the result is not ideal and there are a lot of misjudgments.
Optimization strategy
In order to improve detection accuracy, images need to be preprocessed and a more robust detection method is adopted. The following steps are gradually optimized:
Image Preprocessing: High-resolution image processing is time-consuming and therefore requires optimization. First of all, when reading an image, you can consider reducing the image size and reducing the calculation complexity, but you need to pay attention to the balance between the size reduction ratio and accuracy. You can use the
cv2.resize
function and select the appropriate interpolation method (e.g.cv2.INTER_AREA
for shrinking).Enhanced contrast: To highlight the white circular area, image contrast can be enhanced. You can use histogram equalization (
cv2.equalizeHist
) or CLAHE (Contrast Limited Adaptive Histogram Equalization,cv2.createCLAHE
). CLAHE can better handle local contrast differences.Threshold segmentation: After converting the image to a grayscale graph, use adaptive threshold segmentation (
cv2.adaptiveThreshold
) instead of a simple global threshold segmentation. Adaptive threshold segmentation can better adapt to the brightness changes in different areas of the image. A suitable adaptive method (e.g.cv2.ADAPTIVE_THRESH_GAUSSIAN_C
) and block size can be selected.Morphological operation: Use morphological opening operations (
cv2.morphologyEx
,cv2.MORPH_OPEN
) to remove noise and fine impurities in the image to make the circular area clearer. You need to choose the appropriate structural element size.Contour detection and filtering: Use
cv2.findContours
function to detect image contours. When filtering outlines, interference items can be eliminated based on features such as the contour area, circumference, and circularity, and only contours that conform to the white circular characteristics are retained. The circularity can be calculated using the contour area and perimeter.Minimum circumference: For the filtered contour, you can use
cv2.minEnclosingCircle
function to fit the minimum circumference to obtain the center coordinates and radius.
Improved code framework (the parameters need to be adjusted according to the actual image):
import cv2 import numpy as np image_path = r"C:\Users\17607\Desktop\smls pictures\Pic_20231122151507973.bmp" img = cv2.imread(image_path) img_resized = cv2.resize(img, (img.shape[1] // 4, img.shape[0] // 4), interpolation=cv2.INTER_AREA) #Resize, for example to shrink to 1/4 gray = cv2.cvtColor(img_resized, cv2.COLOR_BGR2GRAY) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) gray = clahe.apply(gray) thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) kernel = np.ones((5,5), np.uint8) opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) contours, _ = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) circles = [] for cnt in contours: area = cv2.contourArea(cnt) perimeter = cv2.arcLength(cnt, True) if perimeter > 0: #Avoid zero-deletion errorscircularity = 4 * np.pi * area / (perimeter ** 2) if area > 100 and circuitry > 0.7: #Adjust the threshold (x,y) according to the actual situation, radius = cv2.minEnclosingCircle(cnt) circles.append(((int(x), int(y)), int(radius))) # Draw the result (remember to adjust the coordinates and radius back to the original image according to the scaling ratio) for (x,y),radius in circles: cv2.circle(img, (x*4, y*4), radius*4, (0,255,0), 2) # The scale is 4, remember to modify cv2.imshow('Detected Circles', img) cv2.waitKey(0) cv2.destroyAllWindows()
Note: Parameters in the code (such as thresholds, kernel size, area, and circularity thresholds for morphological operations) need to be adjusted according to the actual image to obtain the best results. It is recommended to gradually adjust the parameters and observe the results. In addition, consider adding an exception handling mechanism, such as handling the situation where image reading fails. Finally, remember to adjust the coordinates and radius of the detection result back to the original image according to the scaling ratio.
The above is the detailed content of How to optimize processing of high-resolution images in Python to find precise white circular areas?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ToresolvenetworkconnectivityissuesinWindows,resettheTCP/IPstackbyfirstopeningCommandPromptasAdministrator,thenrunningthecommandnetshintipreset,andfinallyrestartingyourcomputertoapplychanges;ifissuespersist,optionallyrunnetshwinsockresetandrebootagain

EnableAppLockerviaGroupPolicybyopeninggpedit.msc,navigatingtoApplicationControlPolicies,creatingdefaultrules,andconfiguringruletypes;2.Createcustomrulesusingpublisher,path,orhashconditions,preferringpublisherrulesforsecurityandflexibility;3.Testrules

Use multiprocessing.Queue to safely pass data between multiple processes, suitable for scenarios of multiple producers and consumers; 2. Use multiprocessing.Pipe to achieve bidirectional high-speed communication between two processes, but only for two-point connections; 3. Use Value and Array to store simple data types in shared memory, and need to be used with Lock to avoid competition conditions; 4. Use Manager to share complex data structures such as lists and dictionaries, which are highly flexible but have low performance, and are suitable for scenarios with complex shared states; appropriate methods should be selected based on data size, performance requirements and complexity. Queue and Manager are most suitable for beginners.

VerifytheWindowsISOisfromMicrosoftandrecreatethebootableUSBusingtheMediaCreationToolorRufuswithcorrectsettings;2.Ensurehardwaremeetsrequirements,testRAMandstoragehealth,anddisconnectunnecessaryperipherals;3.ConfirmBIOS/UEFIsettingsmatchtheinstallatio

Linux is suitable for old hardware, has high security and is customizable, but has weak software compatibility; Windows software is rich and easy to use, but has high resource utilization. 1. In terms of performance, Linux is lightweight and efficient, suitable for old devices; Windows has high hardware requirements. 2. In terms of software, Windows has wider compatibility, especially professional tools and games; Linux needs to use tools to run some software. 3. In terms of security, Linux permission management is stricter and updates are convenient; although Windows is protected, it is still vulnerable to attacks. 4. In terms of difficulty of use, the Linux learning curve is steep; Windows operation is intuitive. Choose according to requirements: choose Linux with performance and security, and choose Windows with compatibility and ease of use.

Bank of America starts digital asset tracking to mark the increase in Ethereum's recognition in mainstream finance. 1. Increase in legality recognition; 2. It may attract institutions to allocate digital assets; 3. Promote the compliance process; 4. Confirm the application prospects and potential value of ETH as a "digital oil"; Ethereum has become the focus because of its huge DApp ecosystem, 1. Upgrade technology to PoS to improve scalability, security and sustainability; 2. Support lending, trading and other financial services as the core of DeFi; 3. Support NFT prosperity and consolidate ecological demand; 4. Expand enterprise-level applications such as supply chain management; 5. EIP-1559 introduces a deflation mechanism to enhance scarcity; top trading platforms include: 1. Binance (trading volume)

Install the corresponding database driver; 2. Use connect() to connect to the database; 3. Create a cursor object; 4. Use execute() or executemany() to execute SQL and use parameterized query to prevent injection; 5. Use fetchall(), etc. to obtain results; 6. Commit() is required after modification; 7. Finally, close the connection or use a context manager to automatically handle it; the complete process ensures that SQL operations are safe and efficient.

Use boto3 to upload files to S3 to install boto3 first and configure AWS credentials; 2. Create a client through boto3.client('s3') and call the upload_file() method to upload local files; 3. You can specify s3_key as the target path, and use the local file name if it is not specified; 4. Exceptions such as FileNotFoundError, NoCredentialsError and ClientError should be handled; 5. ACL, ContentType, StorageClass and Metadata can be set through the ExtraArgs parameter; 6. For memory data, you can use BytesIO to create words
