我每 10 分钟就会在阳光下以 10 厘米指甲的阴影为拍摄对象拍照。但是当白天是第一个早上或最后一个晚上时,你会收到一个挑战,那就是在纸上找到指甲阴影1]1这条线(阴影),当它是淡淡的颜色或像这样苍白时
它不检测线路。但是,当线条颜色丰富或强烈时,我的算法会找到线条(阴影)。我需要线的顶部和底部的坐标来计算线的长度。
我的代码是:
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)
我更改了高斯模糊和边缘值的值,但没有解决我的问题,也没有检测到线条。我什至购买了另一种型号的相机,质量更高,但无法检测线条。
您可以尝试使用自适应阈值来处理照明的变化,沿着这些思路:
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)