带有图像处理的OpenCV如何优化检测线算法?

问题描述 投票:0回答:1

我在纸上找到线条时遇到问题。这条线,当它像这样微弱的颜色或苍白时:

enter image description here

它不检测线路。但是,当线条颜色丰富或强烈时,我的算法会找到该线条。我需要线顶部和底部的 x、y 来从图像中提取数据。

我怎样才能在图像中检测线中的低色线?

我的代码是:

import time
import numpy as np
import cv2
import serial
from math import atan, sqrt, degrees

# Initialize the serial port
ser = serial.Serial('COM3', baudrate=9600, timeout=1)

def captureImage():
    print('Capturing image')
    videoCaptureObject = cv2.VideoCapture(1)

    result = True
    while(result):
        ret, frame = videoCaptureObject.read()
        cv2.imwrite("Newpicture.jpg", frame)
        result = False
    videoCaptureObject.release()
    return frame

def processImage(im):
    print('Processing image')
    image = im

    # Convert image to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # Apply Gaussian blur to reduce noise
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    # Convert grayscale image to binary using Otsu thresholding
    # Apply edge detection
    edges = cv2.Canny(blurred, 50, 150)
    
    # Find contours in the edge-detected image
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    if contours:
        # Get the largest contour (assuming it's the line)
        c = max(contours, key=cv2.contourArea)
        
        # Get the extreme points of the contour (line)
        x1, y1 = c[c[:, :, 0].argmin()][0]
        x2, y2 = c[c[:, :, 0].argmax()][0]
        
        # Calculate the length of the line
        length = sqrt((x2 - x1)**2 + (y2 - y1)**2)

我更改了高斯模糊和边缘值的值,但不回答也不检测线条。我使用另一种型号的相机也无法检测到。线。

python-3.x opencv image-processing
1个回答
0
投票

您可以尝试使用自适应阈值来处理照明的变化,沿着这些思路:

import cv2 as cv

# Load image as greyscale
img = cv.imread('line.jpg', cv.IMREAD_GRAYSCALE)

# Threshold relative to brightness of local 49x49 area
th = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV,49,10)

# Save result
cv.imwrite('result.png', th)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.