Каждые 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)
как я могу удалить отрицательные числа для моего вопроса
Canny — детектор краев. Если вы хотите обнаружить линию, используйте детектор линии, а не детектор краев. Google для «линейного детектора» или «гребневого детектора».