2017-04-07 40 views
0

我正在開發一款智能汽車項目,在檢測到紅色時汽車應該停下來並檢測到綠色,它應該開始運行。我使用Matlab進行顏色檢測,並使用Arduino來運行汽車。但問題是我無法檢測到綠色,代碼只檢測到紅色並停止了車輛。我無法弄清楚問題所在。有關使用Matlab和Arduino檢測紅色和綠色的問題

我的代碼是:

vid = videoinput('winvideo',1 ,'YUY2_320x240'); 

s=serial('COM9','BAUD',9600); 
fopen(s); %open serial port 
set(vid, 'FramesPerTrigger', Inf); 
set(vid, 'ReturnedColorspace', 'rgb') 
vid.FrameGrabInterval = 10; 
start(vid) 
%set a loop that stop after 100 frames of aquisition 
for i=1:100 

IMRED = getsnapshot(vid); % get the snapshot of the current frame 

diff_im = imsubtract(IMRED(:,:,1), rgb2gray(IMRED)); % subtract red component from the grayscale image to extract the red component in image. 
gr=graythresh(diff_im); 

diff_im1 = imsubtract(IMRED(:,:,2), rgb2gray(IMRED)); %subtract green component from the grayscale image to extract the green component in image. 
gr1=graythresh(diff_im1); 

diff_im = medfilt2(diff_im, [3 3]); % median filter to filter the noise. 
diff_im1 = medfilt2(diff_im1, [3 3]); 

% convert the resulting grayscale image into a binary image. 
diff_im = im2bw(diff_im,.18); 
diff_im1 = im2bw(diff_im1,.05); 

% Remove all those pixels less than 300px 
diff_im = bwareaopen(diff_im,300); 
diff_im1 = bwareaopen(diff_im1,300); 

% Label all the connected components in the image 
[bw bw1] = bwlabel(diff_im, 8); 
[L bw2] = bwlabel(diff_im1, 8); 

if (bw1<=0 && bw2 <=0) % if no color detected run forward 
    fprintf(s,100); 

elseif (bw1>=1) % if red detected stop the car 
    while (bw1>=1); 
     fprintf(s,101); 
    end 

    while(~(bw2>=1)) % start the car if green detected 
     fprintf(s,101); 
    end 

    fprintf(s,100); 

    if (bw2>=1) 
     fprintf(s,100); 
    else 
     fprintf(s,101); 
    end 

else 
    fprintf(s,100); 
end 
imshow(IMRED) 
hold on 
hold off 
end 
stop(vid); 
flushdata(vid); 
delete(vid); 
clear vid; 
fclose(s); 
clear all; 
clc 

我得到這樣的輸出:

code output data

+0

您是否注意到您的代碼中沒有評論? –

+0

重複將特定顏色隔離出來,而忽略其餘像素。用它來幫助你解決你的問題。 – rayryeng

回答

0

我猜你正在努力尋找具有高的綠色值的像素,

我在過去嘗試過,因爲在改變照明和曝光條件下決定閾值的難度,所以無法正常工作。相反,嘗試將rgb值轉換爲色相,飽和度和亮度(HSL)或HSV;然後看看給定像素的色調是否接近綠色的色調。這對我來說很有用,因爲它忽略了像素的飽和度和亮度,這兩個值可能會發生很大的變化。

https://en.wikipedia.org/wiki/HSL_and_HSV

https://uk.mathworks.com/help/matlab/ref/rgb2hsv.html

也注意到,對於一些廉價的攝像頭,高強度環保可能不會像綠都在屏幕上。您可能需要手動調整相機的曝光度才能正確讀出色調。

相關問題