我每 10 分钟拍摄一次放在太阳前面的 10 厘米钉子阴影的图像。然而,我在清晨和傍晚时面临着挑战,当时阴影变得微弱而苍白,使我的算法很难检测到它们。这是我试图检测的微弱阴影的示例:
当阴影颜色丰富或强烈时,我的算法成功检测到它。然而,在阴影较弱的情况下,它无法识别该线。我需要获取线的顶部和底部的坐标来计算其长度。
我的代码是:
import time
import numpy as np
import cv2
from math import atan, sqrt, degrees
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)
# Apply a median filter to enhance the line
blurred = cv2.medianBlur(blurred, 5)
# Convert grayscale image to binary using a manually adjusted threshold
_, thresh = cv2.threshold(blurred, 100, 255, cv2.THRESH_BINARY_INV)
# Apply edge detection
edges = cv2.Canny(thresh, 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)
# Print the coordinates and length
print(f"Top: ({x1}, {y1}), Bottom: ({x2}, {y2}), Length: {length}")
# Repeat the process 100 times with a 3-minute interval
for i in range(100):
captureImage()
time.sleep(180) # 3 minutes in seconds
processImage(captureImage())
我调整了高斯模糊和边缘检测的参数,但这些更改并没有解决问题。我什至购买了更高质量的相机,但问题仍然存在。
您可以尝试使用自适应阈值来处理照明的变化,沿着这些思路:
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)