clear ; close all ; clc ;
display = true ;
originAngle = 4 ;
needleLength = 400 ;
curveRadius = 200 ;
kernelSize = 30 ;
w200Center = [1000, 1860] ;
w200OffsetNC = [290, 180] ;
w200width = 800 ;
w200Height = 600 ;
w200MatFile = 'w200_threshold08_template.mat' ;
loaded = load( w200MatFile ) ;
w200Template = -1 + 2 * rot90( double( loaded.thresh08_200 ), 2 ) ;
D_jpg = dir( '*.jpg' ) ;
nFiles = numel( D_jpg ) ;
needleAngles = zeros( nFiles, 1 ) ;
w200RowBnd = round( w200Center(1) + 0.5*[-w200Height, w200Height] ) ;
w200ColBnd = round( w200Center(2) + 0.5*[-w200width, w200width] ) ;
for fId = 1 : nFiles
needleAngles(fId) = NaN ;
I_flat = sum( imread( D_jpg(fId).name ), 3 ) ;
tic ;
w200 = I_flat(w200RowBnd(1):w200RowBnd(2), w200ColBnd(1):w200ColBnd(2)) ;
w200 = w200 > 0.8 * max( w200(:) ) ;
match = conv2( double( w200 ), w200Template, 'same' ) ;
[r, c] = find( match == max( match(:) ) ) ;
if numel( r ) > 1
fprintf( '%-20s: failed to match "200" template.\n', D_jpg(fId).name ) ;
if ~display
continue ;
end
end
matchCenter(1) = r(1) ;
matchCenter(2) = c(1) ;
needleCenter = [w200RowBnd(1) + matchCenter(1) + w200OffsetNC(1), ...
w200ColBnd(1) + matchCenter(2) + w200OffsetNC(2)] ;
curveRowIds = round( needleCenter(1) - curveRadius * cos( 0:0.02:2*pi )) ;
curveColIds = round( needleCenter(2) + curveRadius * sin( 0:0.02:2*pi )) ;
curveSample = I_flat( sub2ind( size(I_flat), curveRowIds, curveColIds )) ;
sampleConv = conv( repmat( curveSample, 1, 3 ), ...
ones( 1, kernelSize )/kernelSize, 'same' ) ;
nSamples = numel( curveSample ) ;
sampleConv = sampleConv(nSamples + (1:nSamples)) ;
needleAngles(fId) = -originAngle + ...
360/nSamples * find( sampleConv == max(sampleConv), 1 ) ;
fprintf( '%-20s: processing time = %.2fs.\n', D_jpg(fId).name, toc ) ;
if display
figure() ;
set( gcf, 'Units', 'normalized', 'Position', [0.1,0.1,0.8,0.8] ) ;
subplot( 2, 2, 1 ) ; hold on ;
imshow( I_flat/max(I_flat(:)) ) ;
plot( needleCenter(2), needleCenter(1), 'xb', curveColIds, curveRowIds, 'r' ) ;
plot( [reshape( [w200ColBnd; w200ColBnd], 1, [] ), w200ColBnd(1)], ...
[w200RowBnd, fliplr(w200RowBnd), w200RowBnd(1)], 'g' ) ;
needleTip = [needleCenter(1) - cosd( needleAngles(fId)+originAngle ) * needleLength, ...
needleCenter(2) + sind( needleAngles(fId)+originAngle ) * needleLength] ;
plot( [needleCenter(2), needleTip(2)], [needleCenter(1), needleTip(1)], ...
'b', 'LineWidth', 3 ) ;
subplot( 2, 2, 2 ) ; hold on ;
imshow( w200 ) ;
plot( matchCenter(2), matchCenter(1), 'rx', 'LineWidth', 3, 'MarkerSize', 10 ) ;
subplot( 2, 2, 3 ) ; hold on ; grid on ;
title( D_jpg(fId).name ) ;
angleSample = 0:360/(nSamples-1):360 ;
plot( angleSample, curveSample, 'b', angleSample, sampleConv, 'r' ) ;
line( [needleAngles(fId) needleAngles(fId)], ylim, 'Color', [0, 1, 0] ) ;
subplot( 2, 2, 4 ) ; hold on ;
set(gca, 'Visible', 'off' ) ;
text( 0.1, 0.5 , sprintf( 'Angle = %.1f°', needleAngles(fId)), 'FontSize', 20 ) ;
end
end
Best Answer