Undefined function or variable in tracking green ball example

I'm attempting to follow the tracking a green ball example found here:
using my built in webcam. When I attempt to run the code I am getting an error undefined function or variable bwbw. I am using the following code for the trackball function:
function [img, bw] = trackball(img, thresh)
r = img(:, :, 1);
g = img(:, :, 2);
b = img(:, :, 3);
justGreen = g - r/2 - b/2;
bw = justGreen > thresh;
[x, y] = find(bw);
if ~isempty(x) && ~isempty(y)
xm = round(mean(x));
ym = round(mean(y));
xx = max(1, xm-5):min(xm+5, size(bw, 1));
yy = max(1, ym-5):min(ym+5, size(bw, 2));
bwbw = zeros(size(bw), 'uint8');
bwbw(xx, yy) = 255;
end
imagesc(justGreen + bwbw);
and am calling it using this code (I've tried running it both from the command window and by creating a script and running it):
function [img, bw] = trackball(img, thresh)
r = img(:, :, 1);
g = img(:, :, 2);
b = img(:, :, 3);
justGreen = g - r/2 - b/2;
bw = justGreen > thresh;
[x, y] = find(bw);
if ~isempty(x) && ~isempty(y)
xm = round(mean(x));
ym = round(mean(y));
xx = max(1, xm-5):min(xm+5, size(bw, 1));
yy = max(1, ym-5):min(ym+5, size(bw, 2));
bwbw = zeros(size(bw), 'uint8');
bwbw(xx, yy) = 255;
end
imagesc(justGreen + bwbw);
I was able to run it successfully once last week without obtaining this error, but now I cannot fix it. I do make sure to create a camera object (using cam = webcam) before I run the loop that captures the snapshots. Any help would be greatly appreciated. Thanks!

 採用された回答

Image Analyst
Image Analyst 2016 年 3 月 22 日
編集済み: Image Analyst 2016 年 3 月 22 日

0 投票

This poorly written code never assigns bwbw in the case where no green is found. To fix, add this line after you threshold it to find bw:
bwbw = zeros(size(bw), 'uint8');
Even better, use my code instead. It's attached.

その他の回答 (1 件)

John D'Errico
John D'Errico 2016 年 3 月 22 日

0 投票

Um, think about how and when the variable bwbw is defined.
[x, y] = find(bw);
if ~isempty(x) && ~isempty(y)
...
bwbw = zeros(size(bw), 'uint8');
bwbw(xx, yy) = 255;
end
Is it possible that the if statement never triggers? Better, is it a fact?
Under what circumstances will that the clause in the if statement not be true?
When you have a problem like this in a function, LEARN TO USE THE DEBUGGER. The debugger is your friend.

カテゴリ

ヘルプ センター および File ExchangeImage Processing Toolbox についてさらに検索

質問済み:

LKR
2016 年 3 月 22 日

コメント済み:

LKR
2016 年 3 月 23 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by