چرا از فضای رنگی مختلف استفاده می کنیم؟

از فضای رنگی مختلف استفاده می کنیم چون این امکان در آن فضای رنگی به ما داده میشه تا بتوینم رنگ دلخواه مان را به راحتی از محدوده دیگر رنگ ها جدا کنیم .فرض کنید که شما قصد دارید رنگ سبز را در تصویر فیلتر نمایید این بازه شامل طیفی می باشد که یک سمت آن سبز تیره و در سمت دیگر آن سبز روشن می باشد برای جدا کردن آن در فضای رنگی RGB این امکان وجود ندارد که شما بتوان به صورت خطی یعنی هر کانال با یک شرط بازه رنگ دلخواه را انتخاب نمائید پس به خاطر چنین مشکلاتی تصویر را به فضای رنگی HSV انتقال می دهیم که این فضا از اجزای Hue (رنگدانه) ،Saturation(اشباع) و Value(روشنایی) تشکیل شده.برای تفکیک رنگ سبز در این فضای رنگی کافیست محدوده Hue خود که مربوط به رنگ مورد نظر را انتخاب کرده و سپس کل محدوه اشباع و در نهایت انتخاب محدوده دلخواه برای روشنایی پس در این فضای رنگی به راحتی تونستید رنگ دلخواه خودتون را انتخاب کنید.

تبدیل فضای رنگی در opencv

در کتابخانه Opencv می تونیم از تابع cvtColor استفاده کنیم.

مثال:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*------------------------------------------------------------------------------------------*\
This file contains material supporting chapter 3 of the cookbook:
Computer Vision Programming using the OpenCV Library
Second Edition
by Robert Laganiere, Packt Publishing, 2013.
 
This program is free software; permission is hereby granted to use, copy, modify,
and distribute this source code, or portions thereof, for any purpose, without fee,
subject to the restriction that the copyright notice may not be removed
or altered from any source or altered source distribution.
The software is released on an as-is basis and without any warranties of any kind.
In particular, the software is not guaranteed to be fault-tolerant or free from failure.
The author disclaims all warranties with regard to this software, any use,
and any consequent failure, is purely the responsibility of the user.
 
Copyright (C) 2013 Robert Laganiere, www.laganiere.name
\*------------------------------------------------------------------------------------------*/
 
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
 
#include <iostream>
#include <vector>
 
void detectHScolor(const cv::Mat& image, // input image
double minHue, double maxHue, // Hue interval
double minSat, double maxSat, // saturation interval
cv::Mat& mask) { // output mask
 
// convert into HSV space
cv::Mat hsv;
cv::cvtColor(image, hsv, CV_BGR2HSV);
 
// split the 3 channels into 3 images
std::vector<cv::Mat> channels;
cv::split(hsv, channels);
// channels[0] is the Hue
// channels[1] is the Saturation
// channels[2] is the Value
 
// Hue masking
cv::Mat mask1; // under maxHue
cv::threshold(channels[0], mask1, maxHue, 255, cv::THRESH_BINARY_INV);
cv::Mat mask2; // over minHue
cv::threshold(channels[0], mask2, minHue, 255, cv::THRESH_BINARY);
 
cv::Mat hueMask; // hue mask
if (minHue < maxHue)
hueMask = mask1 & mask2;
else // if interval crosses the zero-degree axis
hueMask = mask1 | mask2;
 
// Saturation masking
// under maxSat
cv::threshold(channels[1], mask1, maxSat, 255, cv::THRESH_BINARY_INV);
// over minSat
cv::threshold(channels[1], mask2, minSat, 255, cv::THRESH_BINARY);
 
cv::Mat satMask; // saturation mask
satMask = mask1 & mask2;
 
// combined mask
mask = hueMask&satMask;
}
 
int main()
{
// read the image
cv::Mat image= cv::imread("boldt.jpg");
if (!image.data)
return 0;
 
// show original image
cv::namedWindow("Original image");
cv::imshow("Original image",image);
 
// convert into HSV space
cv::Mat hsv;
cv::cvtColor(image, hsv, CV_BGR2HSV);
 
// split the 3 channels into 3 images
std::vector<cv::Mat> channels;
cv::split(hsv,channels);
// channels[0] is the Hue
// channels[1] is the Saturation
// channels[2] is the Value
 
// display value
cv::namedWindow("Value");
cv::imshow("Value",channels[2]);
 
// display saturation
cv::namedWindow("Saturation");
cv::imshow("Saturation",channels[1]);
 
// display hue
cv::namedWindow("Hue");
cv::imshow("Hue",channels[0]);
 
// image with fixed value
cv::Mat newImage;
cv::Mat tmp(channels[2].clone());
// Value channel will be 255 for all pixels
channels[2]= 255;
// merge back the channels
cv::merge(channels,hsv);
// re-convert to BGR
cv::cvtColor(hsv,newImage,CV_HSV2BGR);
 
cv::namedWindow("Fixed Value Image");
cv::imshow("Fixed Value Image",newImage);
 
// image with fixed saturation
channels[1]= 255;
channels[2]= tmp;
cv::merge(channels,hsv);
cv::cvtColor(hsv,newImage,CV_HSV2BGR);
 
cv::namedWindow("Fixed saturation");
cv::imshow("Fixed saturation",newImage);
 
// image with fixed value and fixed saturation
channels[1]= 255;
channels[2]= 255;
cv::merge(channels,hsv);
cv::cvtColor(hsv,newImage,CV_HSV2BGR);
 
cv::namedWindow("Fixed saturation/value");
cv::imshow("Fixed saturation/value",newImage);
 
// Testing skin detection
 
// read the image
image= cv::imread("girl.jpg");
if (!image.data)
return 0;
 
// show original image
cv::namedWindow("Original image");
cv::imshow("Original image",image);
 
// detect skin tone
cv::Mat mask;
detectHScolor(image,
160, 10, // hue from 320 degrees to 20 degrees
25, 166, // saturation from ~0.1 to 0.65
mask);
 
// show masked image
cv::Mat detected(image.size(), CV_8UC3, cv::Scalar(0, 0, 0));
image.copyTo(detected, mask);
cv::imshow("Detection result",detected);
 
// A test comparing luminance and brightness
 
// create linear intensity image
cv::Mat linear(100,256,CV_8U);
for (int i=0; i<256; i++) {
 
linear.col(i)= i;
}
 
// create a Lab image
linear.copyTo(channels[0]);
cv::Mat constante(100,256,CV_8U,cv::Scalar(128));
constante.copyTo(channels[1]);
constante.copyTo(channels[2]);
cv::merge(channels,image);
 
// convert back to BGR
cv::Mat brightness;
cv::cvtColor(image,brightness, CV_Lab2BGR);
cv::split(brightness, channels);
 
// create combined image
cv::Mat combined(200,256, CV_8U);
cv::Mat half1(combined,cv::Rect(0,0,256,100));
linear.copyTo(half1);
cv::Mat half2(combined,cv::Rect(0,100,256,100));
channels[0].copyTo(half2);
 
cv::namedWindow("Luminance vs Brightness");
cv::imshow("Luminance vs Brightness",combined);
 
cv::waitKey();
}

منبع

کد برنامه تشخیص و شمارش خودروهای در حال حرکت در زبان Matlab

در این پروژه سعی داریم با استفاده از روش «رهگیری اهداف چندگانه» اقدام به شناسایی اشیاء در حال حرکت نموده و آنها را شمارش نمائیم. این برنامه می تواند جهت شمارش تعداد خودروهای عبوری، تعداد افراد در حال تردد و… مورد استفاده قرار بگیرد. این الگوریتم توسط شرکت mathwork پیاده سازی گردیده و جهت استفاده علاقه مندان ادامه ارائه می گردد.

باتوجه به توضیحات کامل این پروژه از ذکر توضیحات اضافه اجتناب میکنیم و فقط شرحی مختصر از عماکرد برنامه ارائه می نماییم. ابتدا با استفاده از چند فریم به عنوان نمونه، زمینه(background) را شناسایی می کنیم و سپس به اقدام به تشخیص آبجکت های(foreground) می نماییم. سپس با استفاده از روش کالمن (Kalman) اقدام به رهگیری آبجکت هایی که از مقداری مشخص (اصلاحا blob) بزرگتر هستند می نمائیم.  در ادامه آبجکت ها را رهگیری می کنیم تا هنگامی که از صفحه خارج شوند. نکته جالب توجه این هست که اگر آبجکتی موقتا ناپیدا شود(مثلا زیر پل یا درخت قرار بگیرد) به عنوان «Predicted» برچسب خورده و پس از پیدا شدن مجددا به عنوان همان آبجکت قبلی شناسایی می شود.

 

تشخیص و شمارش خودروهای در حال حرکت

سورس کد برنامه تشخیص و شمارش خودرو:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
%% Multiple Object Tracking Tutorial
% This example shows how to perform automatic detection and motion-based
% tracking of moving objects in a video. It simplifies the example
% <matlab:helpview(fullfile(docroot,'toolbox','vision','vision.map'),'MotionBasedMultiObjectTrackingExample')
% Motion-Based Multiple Object Tracking> and uses the |multiObjectTracker|
% available in Automated Driving System Toolbox.
%
% Copyright 2016 The MathWorks, Inc.
  
%%
% Detection of moving objects and motion-based tracking are important
% components of many computer vision applications, including activity
% recognition, traffic monitoring, and automotive safety. The problem of
% motion-based object tracking can be divided into two parts:
%
% # Detecting moving objects in each frame
% # Tracking the moving objects from frame to frame
%
% The detection of moving objects uses a background subtraction algorithm
% based on Gaussian mixture models. Morphological operations are applied to
% the resulting foreground mask to eliminate noise. Finally, blob analysis
% detects groups of connected pixels, which are likely to correspond to
% moving objects.
%
% The tracking of moving objects from frame to frame is done by the
% |multiObjectTracker| object that is responsible for the following:
%
% # Assigning detections to tracks.
% # Initializing new tracks based on unassigned detections. All tracks are
% initialized as |'Tentative'|, accounting for the possibility that they
% resulted from a false detection.
% # Confirming tracks if they have more than _M_ assigned detections in _N_
% frames.
% # Updating existing tracks based on assigned detections.
% # Coasting (predicting) existing unassigned tracks.
% # Deleting tracks if they have remained unassigned (coasted) for too long.
%
% The assignment of detections to the same object is based solely on
% motion. The motion of each track is estimated by a Kalman filter. The
% filter predicts the track's location in each frame, and determines the
% likelihood of each detection being assigned to each track. To initialize
% the filter that you design, use the |FilterInitializationFcn| property of
% the |multiObjectTracker|.
%
% For more information, see
% <matlab:helpview(fullfile(docroot,'toolbox','vision','vision.map'),'multipleObjectTracking') Multiple Object Tracking>.
%
% This example is a function, with the main body at the top and helper
% routines in the form of
% <matlab:helpview(fullfile(docroot,'toolbox','matlab','matlab_prog','matlab_prog.map'),'nested_functions') nested functions>
% below.
  
function p12_on_video_using_tracking_matlab_sample()
% Create objects used for reading video and displaying the results.
videoObjects = setupVideoObjects('6.mp4');
  
% Create objects used for detecting objects in the foreground of the video.
minBlobArea = 10000; % Minimum blob size, in pixels, to be considered as a detection
detectorObjects = setupDetectorObjects(minBlobArea);
  
%% Create the Multi-Object Tracker
% When creating a |multiObjectTracker|, consider the following:
%
% # |FilterInitializationFcn|: The likely motion and measurement models.
% In this case, the objects are expected to have a constant speed motion.
% The |initDemoFilter| function configures a linear Kalman filter to
% track the motion. See the 'Define a Kalman filter' section for details.
% # |AssignmentThreshold|: How far detections may fall from tracks.
% The default value for this parameter is 30. If there are detections
% that are not assigned to tracks, but should be, increase this value. If
% there are detections that get assigned to tracks that are too far,
% decrease this value.
% # |NumCoastingUpdates|: How long a track is maintained before deletion.
% In this case, since the video has 30 frames per second, a reasonable
% value is about 0.75 seconds (22 frames).
% # |ConfirmationParameters|: The parameters controlling track confirmation.
% A track is initialized with every unassigned detection. Some of these
% detections might be false, so initially, all tracks are |'Tentative'|.
% To confirm a track, it has to be detected at least _M_ out of _N_
% frames. The choice of _M_ and _N_ depends on the visibility of the
% objects. This example assumes a visibility of 6 out of 10 frames.
tracker = multiObjectTracker(...
 'FilterInitializationFcn', @initDemoFilter, ...
 'AssignmentThreshold', 30, ...
 'NumCoastingUpdates', 22, ...
 'ConfirmationParameters', [6 10] ...
 );
  
%% Define a Kalman Filter
% When defining a tracking filter for the motion, complete the following
% steps:
%
% *Step 1: Define the motion model and state*
%
% In this example, use a constant velocity model in a 2-D rectangular
% frame.
%
% # The state is |[x;vx;y;vy]|.
% # The state transition model matrix is |A = [1 dt 0 0; 0 1 0 0; 0 0 1 dt; 0 0 0 1]|.
% # Assume that |dt = 1|.
%
% *Step 2: Define the process noise*
%
% The process noise represents the parts of the process that are not taken
% into account in the model. For example, in a constant velocity model, the
% acceleration is neglected.
%
% *Step 3: Define the measurement model*
%
% In this example, only the position (|[x;y]|) is measured. So, the
% measurement model is |H = [1 0 0 0; 0 0 1 0]|.
%
% Note: To preconfigure these parameters, define the |'MotionModel'|
% property as |'2D Constant Velocity'|.
%
% *Step 4: Initialize the state vector based on the sensor measurement*
%
% In this example, because the measurement is |[x;y]| and the state is
% |[x;vx;y;vy]|, initializing the state vector is straightforward. Because
% there is no measurement of the velocity, initialize the |vx| and |vy|
% components to 0.
%
% *Step 5: Define an initial state covariance*
%
% In this example, the measurements are quite noisy, so define the initial
% state covariance to be quite large: |stateCov = diag([50, 50, 50, 50])|
%
% *Step 6: Create the correct filter*
%
% In this example, all the models are linear, so use |trackingKF| as the
% tracking filter.
 function filter = initDemoFilter(detection)
 % Initialize a Kalman filter for this example.
  
 % Define the initial state.
 state = [detection.Measurement(1); 0; detection.Measurement(2); 0];
  
 % Define the initial state covariance.
 stateCov = diag([50, 50, 50, 50]);
  
 % Create the tracking filter.
 filter = trackingKF('MotionModel', '2D Constant Velocity', ...
 'State', state, ...
 'StateCovariance', stateCov, ...
 'MeasurementNoise', detection.MeasurementNoise(1:2,1:2) ...
 );
 end
  
%%%
% The following loop runs the video clip, detects moving objects in the
% video, and tracks them across video frames.
  
% Count frames to create a sense of time.
frameCount = 0;
while hasFrame(videoObjects.reader)
 % Read a video frame and detect objects in it.
 frameCount = frameCount + 1; % Promote frame count
 frame = readFrame(videoObjects.reader); % Read frame
 [detections, mask] = detectObjects(detectorObjects, frame); % Detect objects in video frame
  
 % Run the tracker on the preprocessed detections.
 confirmedTracks = updateTracks(tracker, detections, frameCount);
  
 % Display the tracking results on the video.
 displayTrackingResults(videoObjects, confirmedTracks, frame, mask);
end
%% Create Video Objects
% Create objects used for reading and displaying the video frames.
  
 function videoObjects = setupVideoObjects(filename)
 % Initialize video I/O
 % Create objects for reading a video from a file, drawing the tracked
 % objects in each frame, and playing the video.
  
 % Create a video file reader.
 videoObjects.reader = VideoReader(filename);
  
 % Create two video players: one to display the video,
 % and one to display the foreground mask.
 videoObjects.maskPlayer = vision.VideoPlayer('Position', [20, 400, 700, 400]);
 videoObjects.videoPlayer = vision.VideoPlayer('Position', [740, 400, 700, 400]);
 end
  
%% Create Detector Objects
% Create objects used for detecting foreground objects.
% Use |minBlobArea| to define the size of the blob, in pixels, that is
% considered to be a detection.
%
% * Increase |minBlobArea| to avoid detecting small blobs, which are more
% likely to be false detections, or if several detections are created for
% the same object due to partial occlusion.
% * Decrease |minBlobArea| if objects are detected too late or not at all.
  
 function detectorObjects = setupDetectorObjects(minBlobArea)
 % Create System objects for foreground detection and blob analysis
  
 % The foreground detector segments moving objects from the
 % background. It outputs a binary mask, where the pixel value of 1
 % corresponds to the foreground and the value of 0 corresponds to
 % the background.
  
 detectorObjects.detector = vision.ForegroundDetector('NumGaussians', 3, ...
 'NumTrainingFrames', 40, 'MinimumBackgroundRatio', 0.7);
  
 % Connected groups of foreground pixels are likely to correspond to
 % moving objects. The blob analysis System object finds such
 % groups (called 'blobs' or 'connected components') and computes
 % their characteristics, such as their areas, centroids, and the
 % bounding boxes.
  
 detectorObjects.blobAnalyzer = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
 'AreaOutputPort', true, 'CentroidOutputPort', true, ...
 'MinimumBlobArea', minBlobArea);
 end
  
%% Detect Objects
% The |detectObjects| function returns the centroids and the bounding boxes
% of the detected objects as a list of |objectDetection| objects. You can
% supply this list as an input to the |multiObjectTracker|. The
% |detectObjects| function also returns the binary mask, which has the same
% size as the input frame. Pixels with a value of 1 correspond to the
% foreground. Pixels with a value of 0 correspond to the background.
%
% The function performs motion segmentation using the foreground detector.
% It then performs morphological operations on the resulting binary mask to
% remove noisy pixels and to fill the holes in the remaining blobs.
%
% When creating the |objectDetection| list, the |frameCount| serves as the
% time input, and the centroids of the detected blobs serve as the
% measurement. The list also has two optional name-value pairs:
%
% * |MeasurementNoise| - Blob detection is noisy, and this example defines
% a large measurement noise value.
% * |ObjectAttributes| - The detected bounding boxes that get passed to the
% track display are added to this argument.
  
 function [detections, mask] = detectObjects(detectorObjects, frame)
 % Expected uncertainty (noise) for the blob centroid.
 measurementNoise = 100*eye(2);
 % Detect foreground.
 mask = detectorObjects.detector.step(frame);
  
 % Apply morphological operations to remove noise and fill in holes.
 mask = imopen(mask, strel('rectangle', [9, 9]));
 mask = imclose(mask, strel('rectangle', [10, 10]));
 mask=bwareaopen(mask,1500);
 mask = imfill(mask, 'holes');
  
 % Perform blob analysis to find connected components.
 [~, centroids, bboxes] = detectorObjects.blobAnalyzer.step(mask);
  
 % Formulate the detections as a list of objectDetection objects.
 numDetections = size(centroids, 1);
 detections = cell(numDetections, 1);
 for i = 1:numDetections
 detections{i} = objectDetection(frameCount, centroids(i,:), ...
 'MeasurementNoise', measurementNoise, ...
 'ObjectAttributes', {bboxes(i,:)});
 end
 end
  
%% Display Tracking Results
% The |displayTrackingResults| function draws a bounding box and label ID
% for each track on the video frame and foreground mask. It then displays
% the frame and the mask in their respective video players.
  
 function displayTrackingResults(videoObjects, confirmedTracks, frame, mask)
 % Convert the frame and the mask to uint8 RGB.
 frame = im2uint8(frame);
 mask = uint8(repmat(mask, [1, 1, 3])) .* 255;
  
 if ~isempty(confirmedTracks)
 % Display the objects. If an object has not been detected
 % in this frame, display its predicted bounding box.
 numRelTr = numel(confirmedTracks);
 boxes = zeros(numRelTr, 4);
 ids = zeros(numRelTr, 1, 'int32');
 predictedTrackInds = zeros(numRelTr, 1);
 for tr = 1:numRelTr
 % Get bounding boxes.
 boxes(tr, : ) = confirmedTracks(tr).ObjectAttributes{1}{1};
  
 % Get IDs.
 ids(tr) = confirmedTracks(tr).TrackID;
  
 if confirmedTracks(tr).IsCoasted
 predictedTrackInds(tr) = tr;
 end
 end
  
 predictedTrackInds = predictedTrackInds(predictedTrackInds > 0);
  
 % Create labels for objects that display the predicted rather
 % than the actual location.
 labels = cellstr(int2str(ids));
  
 isPredicted = cell(size(labels));
 isPredicted(predictedTrackInds) = {' predicted'};
 labels = strcat(labels, isPredicted);
  
 % Draw the objects on the frame.
 frame = insertObjectAnnotation(frame, 'rectangle', boxes, labels);
  
 % Draw the objects on the mask.
 mask = insertObjectAnnotation(mask, 'rectangle', boxes, labels);
 end
  
 % Display the mask and the frame.
 videoObjects.maskPlayer.step(mask);
 videoObjects.videoPlayer.step(frame);
 end
displayEndOfDemoMessage(mfilename)
end
%% Summary
% In this example, you created a motion-based system for detecting and
% tracking multiple moving objects. Try using a different video to see if
% you can detect and track objects. Try modifying the parameters of the
% |multiObjectTracker|.
%
% The tracking in this example was based solely on motion, with the
% assumption that all objects move in a straight line with constant speed.
% When the motion of an object significantly deviates from this model, the
% example can produce tracking errors. Notice the mistake in tracking the
% person occluded by the tree.
%
% You can reduce the likelihood of tracking errors by using a more complex
% motion model, such as constant acceleration or constant turn. To do that,
% try defining a different tracking filter, such as |trackingEKF| or
% |trackingUKF|.

تشخیص و شمارش خودروهای در حال حرکت

 

منبع:

https://www.mathworks.com/

 

جهت دانلود بر روی لینک زیر کلیک نمایید.

تشخیص و شمارش خودروهای درحال حرکت

ویدئوی پیوست برنامه تشخیص و شمارش خودورهای در حال حرکت

رمز فایل : behsanandish.com

 

 

مرحله 4: سرکوب لبه های غیر حداکثر

آخرین مرحله، پیدا کردن لبه های ضعیف که موازی با لبه های قوی هستند و از بین بردن آنهاست. این عمل، با بررسی پیکسل های عمود بر یک پیکسل لبه خاص و حذف لبه های غیر حداکثرانجام شده است. کد مورد استفاده بسیار مشابه کد ردیابی لبه است.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
&lt;/pre&gt;
&lt;pre&gt;#include "stdafx.h"
#include "tripod.h"
#include "tripodDlg.h"
 
#include "LVServerDefs.h"
#include "math.h"
#include &lt;fstream&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
 
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
using namespace std;
 
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
 
class CAboutDlg : public CDialog
{
public:
    CAboutDlg();
 
// Dialog Data
    //{{AFX_DATA(CAboutDlg)
    enum { IDD = IDD_ABOUTBOX };
    //}}AFX_DATA
 
    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CAboutDlg)
    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
    //}}AFX_VIRTUAL
 
// Implementation
protected:
    //{{AFX_MSG(CAboutDlg)
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()
};
 
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
    //{{AFX_DATA_INIT(CAboutDlg)
    //}}AFX_DATA_INIT
}
 
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CAboutDlg)
    //}}AFX_DATA_MAP
}
 
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
    //{{AFX_MSG_MAP(CAboutDlg)
        // No message handlers
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/////////////////////////////////////////////////////////////////////////////
// CTripodDlg dialog
 
CTripodDlg::CTripodDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CTripodDlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CTripodDlg)
        // NOTE: the ClassWizard will add member initialization here
    //}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    m_hIcon = AfxGetApp()-&gt;LoadIcon(IDR_MAINFRAME);
 
    //////////////// Set destination BMP to NULL first
    m_destinationBitmapInfoHeader = NULL;
 
}
 
////////////////////// Additional generic functions
 
static unsigned PixelBytes(int w, int bpp)
{
    return (w * bpp + 7) / 8;
}
 
static unsigned DibRowSize(int w, int bpp)
{
    return (w * bpp + 31) / 32 * 4;
}
 
static unsigned DibRowSize(LPBITMAPINFOHEADER pbi)
{
    return DibRowSize(pbi-&gt;biWidth, pbi-&gt;biBitCount);
}
 
static unsigned DibRowPadding(int w, int bpp)
{
    return DibRowSize(w, bpp) - PixelBytes(w, bpp);
}
 
static unsigned DibRowPadding(LPBITMAPINFOHEADER pbi)
{
    return DibRowPadding(pbi-&gt;biWidth, pbi-&gt;biBitCount);
}
 
static unsigned DibImageSize(int w, int h, int bpp)
{
    return h * DibRowSize(w, bpp);
}
 
static size_t DibSize(int w, int h, int bpp)
{
    return sizeof (BITMAPINFOHEADER) + DibImageSize(w, h, bpp);
}
 
/////////////////////// end of generic functions
 
 
void CTripodDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CTripodDlg)
    DDX_Control(pDX, IDC_PROCESSEDVIEW, m_cVideoProcessedView);
    DDX_Control(pDX, IDC_UNPROCESSEDVIEW, m_cVideoUnprocessedView);
    //}}AFX_DATA_MAP
}
 
BEGIN_MESSAGE_MAP(CTripodDlg, CDialog)
    //{{AFX_MSG_MAP(CTripodDlg)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_BN_CLICKED(IDEXIT, OnExit)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/////////////////////////////////////////////////////////////////////////////
// CTripodDlg message handlers
 
BOOL CTripodDlg::OnInitDialog()
{
    CDialog::OnInitDialog();
 
    // Add "About..." menu item to system menu.
 
    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX &amp; 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX &lt; 0xF000);
 
    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        CString strAboutMenu;
        strAboutMenu.LoadString(IDS_ABOUTBOX);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu-&gt;AppendMenu(MF_SEPARATOR);
            pSysMenu-&gt;AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }
 
    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon
     
    // TODO: Add extra initialization here
 
    // For Unprocessed view videoportal (top one)
    char sRegUnprocessedView[] = "HKEY_LOCAL_MACHINE\\Software\\UnprocessedView";
    m_cVideoUnprocessedView.PrepareControl("UnprocessedView", sRegUnprocessedView, 0 );
    m_cVideoUnprocessedView.EnableUIElements(UIELEMENT_STATUSBAR,0,TRUE);
    m_cVideoUnprocessedView.ConnectCamera2();
    m_cVideoUnprocessedView.SetEnablePreview(TRUE);
 
    // For binary view videoportal (bottom one)
    char sRegProcessedView[] = "HKEY_LOCAL_MACHINE\\Software\\ProcessedView";
    m_cVideoProcessedView.PrepareControl("ProcessedView", sRegProcessedView, 0 );  
    m_cVideoProcessedView.EnableUIElements(UIELEMENT_STATUSBAR,0,TRUE);
    m_cVideoProcessedView.ConnectCamera2();
    m_cVideoProcessedView.SetEnablePreview(TRUE);
 
    // Initialize the size of binary videoportal
    m_cVideoProcessedView.SetPreviewMaxHeight(240);
    m_cVideoProcessedView.SetPreviewMaxWidth(320);
 
    // Uncomment if you wish to fix the live videoportal's size
    // m_cVideoUnprocessedView.SetPreviewMaxHeight(240);
    // m_cVideoUnprocessedView.SetPreviewMaxWidth(320);
 
    // Find the screen coodinates of the binary videoportal
    m_cVideoProcessedView.GetWindowRect(m_rectForProcessedView);
    ScreenToClient(m_rectForProcessedView);
    allocateDib(CSize(320, 240));
 
    // Start grabbing frame data for Procssed videoportal (bottom one)
    m_cVideoProcessedView.StartVideoHook(0);
 
    return TRUE;  // return TRUE  unless you set the focus to a control
}
 
void CTripodDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID &amp; 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        dlgAbout.DoModal();
    }
    else
    {
        CDialog::OnSysCommand(nID, lParam);
    }
}
 
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.
 
void CTripodDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting
 
        SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
 
        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&amp;rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
 
        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}
 
// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTripodDlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}
 
void CTripodDlg::OnExit()
{
    // TODO: Add your control notification handler code here
 
    // Kill live view videoportal (top one)
    m_cVideoUnprocessedView.StopVideoHook(0);
    m_cVideoUnprocessedView.DisconnectCamera();
     
    // Kill binary view videoportal (bottom one)
    m_cVideoProcessedView.StopVideoHook(0);
    m_cVideoProcessedView.DisconnectCamera();  
 
    // Kill program
    DestroyWindow();   
 
     
 
}
 
BEGIN_EVENTSINK_MAP(CTripodDlg, CDialog)
    //{{AFX_EVENTSINK_MAP(CTripodDlg)
    ON_EVENT(CTripodDlg, IDC_PROCESSEDVIEW, 1 /* PortalNotification */, OnPortalNotificationProcessedview, VTS_I4 VTS_I4 VTS_I4 VTS_I4)
    //}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()
 
void CTripodDlg::OnPortalNotificationProcessedview(long lMsg, long lParam1, long lParam2, long lParam3)
{
    // TODO: Add your control notification handler code here
     
    // This function is called at the camera's frame rate
     
#define NOTIFICATIONMSG_VIDEOHOOK   10
 
    // Declare some useful variables
    // QCSDKMFC.pdf (Quickcam MFC documentation) p. 103 explains the variables lParam1, lParam2, lParam3 too
     
    LPBITMAPINFOHEADER lpBitmapInfoHeader; // Frame's info header contains info like width and height
    LPBYTE lpBitmapPixelData; // This pointer-to-long will point to the start of the frame's pixel data
    unsigned long lTimeStamp; // Time when frame was grabbed
 
    switch(lMsg) {
        case NOTIFICATIONMSG_VIDEOHOOK:
            {
                lpBitmapInfoHeader = (LPBITMAPINFOHEADER) lParam1;
                lpBitmapPixelData = (LPBYTE) lParam2;
                lTimeStamp = (unsigned long) lParam3;
 
                grayScaleTheFrameData(lpBitmapInfoHeader, lpBitmapPixelData);
                doMyImageProcessing(lpBitmapInfoHeader); // Place where you'd add your image processing code
                displayMyResults(lpBitmapInfoHeader);
 
            }
            break;
 
        default:
            break;
    }  
}
 
void CTripodDlg::allocateDib(CSize sz)
{
    // Purpose: allocate information for a device independent bitmap (DIB)
    // Called from OnInitVideo
 
    if(m_destinationBitmapInfoHeader) {
        free(m_destinationBitmapInfoHeader);
        m_destinationBitmapInfoHeader = NULL;
    }
 
    if(sz.cx | sz.cy) {
        m_destinationBitmapInfoHeader = (LPBITMAPINFOHEADER)malloc(DibSize(sz.cx, sz.cy, 24));
        ASSERT(m_destinationBitmapInfoHeader);
        m_destinationBitmapInfoHeader-&gt;biSize = sizeof(BITMAPINFOHEADER);
        m_destinationBitmapInfoHeader-&gt;biWidth = sz.cx;
        m_destinationBitmapInfoHeader-&gt;biHeight = sz.cy;
        m_destinationBitmapInfoHeader-&gt;biPlanes = 1;
        m_destinationBitmapInfoHeader-&gt;biBitCount = 24;
        m_destinationBitmapInfoHeader-&gt;biCompression = 0;
        m_destinationBitmapInfoHeader-&gt;biSizeImage = DibImageSize(sz.cx, sz.cy, 24);
        m_destinationBitmapInfoHeader-&gt;biXPelsPerMeter = 0;
        m_destinationBitmapInfoHeader-&gt;biYPelsPerMeter = 0;
        m_destinationBitmapInfoHeader-&gt;biClrImportant = 0;
        m_destinationBitmapInfoHeader-&gt;biClrUsed = 0;
    }
}
 
void CTripodDlg::displayMyResults(LPBITMAPINFOHEADER lpThisBitmapInfoHeader)
{
    // displayMyResults: Displays results of doMyImageProcessing() in the videoport
    // Notes: StretchDIBits stretches a device-independent bitmap to the appropriate size
 
    CDC             *pDC;   // Device context to display bitmap data
     
    pDC = GetDC(); 
    int nOldMode = SetStretchBltMode(pDC-&gt;GetSafeHdc(),COLORONCOLOR);
 
    StretchDIBits(
        pDC-&gt;GetSafeHdc(),
        m_rectForProcessedView.left,                // videoportal left-most coordinate
        m_rectForProcessedView.top,                 // videoportal top-most coordinate
        m_rectForProcessedView.Width(),             // videoportal width
        m_rectForProcessedView.Height(),            // videoportal height
        0,                                          // Row position to display bitmap in videoportal
        0,                                          // Col position to display bitmap in videoportal
        lpThisBitmapInfoHeader-&gt;biWidth,         // m_destinationBmp's number of columns
        lpThisBitmapInfoHeader-&gt;biHeight,            // m_destinationBmp's number of rows
        m_destinationBmp,                           // The bitmap to display; use the one resulting from doMyImageProcessing
        (BITMAPINFO*)m_destinationBitmapInfoHeader, // The bitmap's header info e.g. width, height, number of bits etc
        DIB_RGB_COLORS,                             // Use default 24-bit color table
        SRCCOPY                                     // Just display
    );
  
    SetStretchBltMode(pDC-&gt;GetSafeHdc(),nOldMode);
 
    ReleaseDC(pDC);
 
    // Note: 04/24/02 - Added the following:
    // Christopher Wagner cwagner@fas.harvard.edu noticed that memory wasn't being freed
 
    // Recall OnPortalNotificationProcessedview, which gets called everytime
    // a frame of data arrives, performs 3 steps:
    // (1) grayScaleTheFrameData - which mallocs m_destinationBmp
    // (2) doMyImageProcesing
    // (3) displayMyResults - which we're in now
    // Since we're finished with the memory we malloc'ed for m_destinationBmp
    // we should free it:
     
    free(m_destinationBmp);
 
    // End of adds
}
 
void CTripodDlg::grayScaleTheFrameData(LPBITMAPINFOHEADER lpThisBitmapInfoHeader, LPBYTE lpThisBitmapPixelData)
{
 
    // grayScaleTheFrameData: Called by CTripodDlg::OnPortalNotificationBinaryview
    // Task: Read current frame pixel data and computes a grayscale version
 
    unsigned int    W, H;             // Width and Height of current frame [pixels]
    BYTE            *sourceBmp;       // Pointer to current frame of data
    unsigned int    row, col;
    unsigned long   i;
    BYTE            grayValue;
 
    BYTE            redValue;
    BYTE            greenValue;
    BYTE            blueValue;
 
    W = lpThisBitmapInfoHeader-&gt;biWidth;  // biWidth: number of columns
    H = lpThisBitmapInfoHeader-&gt;biHeight; // biHeight: number of rows
 
    // Store pixel data in row-column vector format
    // Recall that each pixel requires 3 bytes (red, blue and green bytes)
    // m_destinationBmp is a protected member and declared in binarizeDlg.h
 
    m_destinationBmp = (BYTE*)malloc(H*3*W*sizeof(BYTE));
 
    // Point to the current frame's pixel data
    sourceBmp = lpThisBitmapPixelData;
 
    for (row = 0; row &lt; H; row++) {
        for (col = 0; col &lt; W; col++) {
 
            // Recall each pixel is composed of 3 bytes
            i = (unsigned long)(row*3*W + 3*col);
         
            // The source pixel has a blue, green andred value:
            blueValue  = *(sourceBmp + i);
            greenValue = *(sourceBmp + i + 1);
            redValue   = *(sourceBmp + i + 2);
 
            // A standard equation for computing a grayscale value based on RGB values
            grayValue = (BYTE)(0.299*redValue + 0.587*greenValue + 0.114*blueValue);
 
            // The destination BMP will be a grayscale version of the source BMP
            *(m_destinationBmp + i)     = grayValue;
            *(m_destinationBmp + i + 1) = grayValue;
            *(m_destinationBmp + i + 2) = grayValue;
             
        }
    }
}
 
 
void CTripodDlg::doMyImageProcessing(LPBITMAPINFOHEADER lpThisBitmapInfoHeader)
{
    // doMyImageProcessing:  This is where you'd write your own image processing code
    // Task: Read a pixel's grayscale value and process accordingly
 
    unsigned int    W, H;           // Width and Height of current frame [pixels]
    unsigned int    row, col;       // Pixel's row and col positions
    unsigned long   i;              // Dummy variable for row-column vector
    int     upperThreshold = 60;    // Gradient strength nessicary to start edge
    int     lowerThreshold = 30;    // Minimum gradient strength to continue edge
    unsigned long iOffset;          // Variable to offset row-column vector during sobel mask
    int rowOffset;                  // Row offset from the current pixel
    int colOffset;                  // Col offset from the current pixel
    int rowTotal = 0;               // Row position of offset pixel
    int colTotal = 0;               // Col position of offset pixel
    int Gx;                         // Sum of Sobel mask products values in the x direction
    int Gy;                         // Sum of Sobel mask products values in the y direction
    float thisAngle;                // Gradient direction based on Gx and Gy
    int newAngle;                   // Approximation of the gradient direction
    bool edgeEnd;                   // Stores whether or not the edge is at the edge of the possible image
    int GxMask[3][3];               // Sobel mask in the x direction
    int GyMask[3][3];               // Sobel mask in the y direction
    int newPixel;                   // Sum pixel values for gaussian
    int gaussianMask[5][5];         // Gaussian mask
 
    W = lpThisBitmapInfoHeader-&gt;biWidth;  // biWidth: number of columns
    H = lpThisBitmapInfoHeader-&gt;biHeight; // biHeight: number of rows
     
    for (row = 0; row &lt; H; row++) {
        for (col = 0; col &lt; W; col++) {
            edgeDir[row][col] = 0;
        }
    }
 
    /* Declare Sobel masks */
    GxMask[0][0] = -1; GxMask[0][1] = 0; GxMask[0][2] = 1;
    GxMask[1][0] = -2; GxMask[1][1] = 0; GxMask[1][2] = 2;
    GxMask[2][0] = -1; GxMask[2][1] = 0; GxMask[2][2] = 1;
     
    GyMask[0][0] =  1; GyMask[0][1] =  2; GyMask[0][2] =  1;
    GyMask[1][0] =  0; GyMask[1][1] =  0; GyMask[1][2] =  0;
    GyMask[2][0] = -1; GyMask[2][1] = -2; GyMask[2][2] = -1;
 
    /* Declare Gaussian mask */
    gaussianMask[0][0] = 2;     gaussianMask[0][1] = 4;     gaussianMask[0][2] = 5;     gaussianMask[0][3] = 4;     gaussianMask[0][4] = 2;
    gaussianMask[1][0] = 4;     gaussianMask[1][1] = 9;     gaussianMask[1][2] = 12;    gaussianMask[1][3] = 9;     gaussianMask[1][4] = 4;
    gaussianMask[2][0] = 5;     gaussianMask[2][1] = 12;    gaussianMask[2][2] = 15;    gaussianMask[2][3] = 12;    gaussianMask[2][4] = 2;
    gaussianMask[3][0] = 4;     gaussianMask[3][1] = 9;     gaussianMask[3][2] = 12;    gaussianMask[3][3] = 9;     gaussianMask[3][4] = 4;
    gaussianMask[4][0] = 2;     gaussianMask[4][1] = 4;     gaussianMask[4][2] = 5;     gaussianMask[4][3] = 4;     gaussianMask[4][4] = 2;
     
 
    /* Gaussian Blur */
    for (row = 2; row &lt; H-2; row++) {
        for (col = 2; col &lt; W-2; col++) {
            newPixel = 0;
            for (rowOffset=-2; rowOffset&lt;=2; rowOffset++) {
                for (colOffset=-2; colOffset&lt;=2; colOffset++) {
                    rowTotal = row + rowOffset;
                    colTotal = col + colOffset;
                    iOffset = (unsigned long)(rowTotal*3*W + colTotal*3);
                    newPixel += (*(m_destinationBmp + iOffset)) * gaussianMask[2 + rowOffset][2 + colOffset];
                }
            }
            i = (unsigned long)(row*3*W + col*3);
            *(m_destinationBmp + i) = newPixel / 159;
        }
    }
 
    /* Determine edge directions and gradient strengths */
    for (row = 1; row &lt; H-1; row++) {
        for (col = 1; col &lt; W-1; col++) {
            i = (unsigned long)(row*3*W + 3*col);
            Gx = 0;
            Gy = 0;
            /* Calculate the sum of the Sobel mask times the nine surrounding pixels in the x and y direction */
            for (rowOffset=-1; rowOffset&lt;=1; rowOffset++) {
                for (colOffset=-1; colOffset&lt;=1; colOffset++) {
                    rowTotal = row + rowOffset;
                    colTotal = col + colOffset;
                    iOffset = (unsigned long)(rowTotal*3*W + colTotal*3);
                    Gx = Gx + (*(m_destinationBmp + iOffset) * GxMask[rowOffset + 1][colOffset + 1]);
                    Gy = Gy + (*(m_destinationBmp + iOffset) * GyMask[rowOffset + 1][colOffset + 1]);
                }
            }
 
            gradient[row][col] = sqrt(pow(Gx,2.0) + pow(Gy,2.0));   // Calculate gradient strength         
            thisAngle = (atan2(Gx,Gy)/3.14159) * 180.0;     // Calculate actual direction of edge
             
            /* Convert actual edge direction to approximate value */
            if ( ( (thisAngle &lt; 22.5) &amp;&amp; (thisAngle &gt; -22.5) ) || (thisAngle &gt; 157.5) || (thisAngle &lt; -157.5) )
                newAngle = 0;
            if ( ( (thisAngle &gt; 22.5) &amp;&amp; (thisAngle &lt; 67.5) ) || ( (thisAngle &lt; -112.5) &amp;&amp; (thisAngle &gt; -157.5) ) )
                newAngle = 45;
            if ( ( (thisAngle &gt; 67.5) &amp;&amp; (thisAngle &lt; 112.5) ) || ( (thisAngle &lt; -67.5) &amp;&amp; (thisAngle &gt; -112.5) ) )
                newAngle = 90;
            if ( ( (thisAngle &gt; 112.5) &amp;&amp; (thisAngle &lt; 157.5) ) || ( (thisAngle &lt; -22.5) &amp;&amp; (thisAngle &gt; -67.5) ) )
                newAngle = 135;
                 
            edgeDir[row][col] = newAngle;       // Store the approximate edge direction of each pixel in one array
        }
    }
 
    /* Trace along all the edges in the image */
    for (row = 1; row &lt; H - 1; row++) {
        for (col = 1; col &lt; W - 1; col++) {
            edgeEnd = false;
            if (gradient[row][col] &gt; upperThreshold) {       // Check to see if current pixel has a high enough gradient strength to be part of an edge
                /* Switch based on current pixel's edge direction */
                switch (edgeDir[row][col]){    
                    case 0:
                        findEdge(0, 1, row, col, 0, lowerThreshold);
                        break;
                    case 45:
                        findEdge(1, 1, row, col, 45, lowerThreshold);
                        break;
                    case 90:
                        findEdge(1, 0, row, col, 90, lowerThreshold);
                        break;
                    case 135:
                        findEdge(1, -1, row, col, 135, lowerThreshold);
                        break;
                    default :
                        i = (unsigned long)(row*3*W + 3*col);
                        *(m_destinationBmp + i) =
                        *(m_destinationBmp + i + 1) =
                        *(m_destinationBmp + i + 2) = 0;
                        break;
                    }
                }
            else {
                i = (unsigned long)(row*3*W + 3*col);
                    *(m_destinationBmp + i) =
                    *(m_destinationBmp + i + 1) =
                    *(m_destinationBmp + i + 2) = 0;
            }  
        }
    }
     
    /* Suppress any pixels not changed by the edge tracing */
    for (row = 0; row &lt; H; row++) {
        for (col = 0; col &lt; W; col++) { 
            // Recall each pixel is composed of 3 bytes
            i = (unsigned long)(row*3*W + 3*col);
            // If a pixel's grayValue is not black or white make it black
            if( ((*(m_destinationBmp + i) != 255) &amp;&amp; (*(m_destinationBmp + i) != 0)) || ((*(m_destinationBmp + i + 1) != 255) &amp;&amp; (*(m_destinationBmp + i + 1) != 0)) || ((*(m_destinationBmp + i + 2) != 255) &amp;&amp; (*(m_destinationBmp + i + 2) != 0)) )
                *(m_destinationBmp + i) =
                *(m_destinationBmp + i + 1) =
                *(m_destinationBmp + i + 2) = 0; // Make pixel black
        }
    }
 
    /* Non-maximum Suppression */
    for (row = 1; row &lt; H - 1; row++) {
        for (col = 1; col &lt; W - 1; col++) {
            i = (unsigned long)(row*3*W + 3*col);
            if (*(m_destinationBmp + i) == 255) {       // Check to see if current pixel is an edge
                /* Switch based on current pixel's edge direction */
                switch (edgeDir[row][col]) {       
                    case 0:
                        suppressNonMax( 1, 0, row, col, 0, lowerThreshold);
                        break;
                    case 45:
                        suppressNonMax( 1, -1, row, col, 45, lowerThreshold);
                        break;
                    case 90:
                        suppressNonMax( 0, 1, row, col, 90, lowerThreshold);
                        break;
                    case 135:
                        suppressNonMax( 1, 1, row, col, 135, lowerThreshold);
                        break;
                    default :
                        break;
                }
            }  
        }
    }
     
}
 
void CTripodDlg::findEdge(int rowShift, int colShift, int row, int col, int dir, int lowerThreshold)
{
    int W = 320;
    int H = 240;
    int newRow;
    int newCol;
    unsigned long i;
    bool edgeEnd = false;
 
    /* Find the row and column values for the next possible pixel on the edge */
    if (colShift &lt; 0) {
        if (col &gt; 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col &lt; W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;     // If the next pixel would be off image, don't do the while loop
    if (rowShift &lt; 0) {
        if (row &gt; 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row &lt; H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
         
    /* Determine edge directions and gradient strengths */
    while ( (edgeDir[newRow][newCol]==dir) &amp;&amp; !edgeEnd &amp;&amp; (gradient[newRow][newCol] &gt; lowerThreshold) ) {
        /* Set the new pixel as white to show it is an edge */
        i = (unsigned long)(newRow*3*W + 3*newCol);
        *(m_destinationBmp + i) =
        *(m_destinationBmp + i + 1) =
        *(m_destinationBmp + i + 2) = 255;
        if (colShift &lt; 0) {
            if (newCol &gt; 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol &lt; W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift &lt; 0) {
            if (newRow &gt; 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow &lt; H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
    }  
}
 
void CTripodDlg::suppressNonMax(int rowShift, int colShift, int row, int col, int dir, int lowerThreshold)
{
    int W = 320;
    int H = 240;
    int newRow = 0;
    int newCol = 0;
    unsigned long i;
    bool edgeEnd = false;
    float nonMax[320][3];           // Temporarily stores gradients and positions of pixels in parallel edges
    int pixelCount = 0;                 // Stores the number of pixels in parallel edges
    int count;                      // A for loop counter
    int max[3];                     // Maximum point in a wide edge
     
    if (colShift &lt; 0) {
        if (col &gt; 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col &lt; W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;     // If the next pixel would be off image, don't do the while loop
    if (rowShift &lt; 0) {
        if (row &gt; 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row &lt; H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
    i = (unsigned long)(newRow*3*W + 3*newCol);
    /* Find non-maximum parallel edges tracing up */
    while ((edgeDir[newRow][newCol] == dir) &amp;&amp; !edgeEnd &amp;&amp; (*(m_destinationBmp + i) == 255)) {
        if (colShift &lt; 0) {
            if (newCol &gt; 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol &lt; W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift &lt; 0) {
            if (newRow &gt; 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow &lt; H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
        nonMax[pixelCount][0] = newRow;
        nonMax[pixelCount][1] = newCol;
        nonMax[pixelCount][2] = gradient[newRow][newCol];
        pixelCount++;
        i = (unsigned long)(newRow*3*W + 3*newCol);
    }
 
    /* Find non-maximum parallel edges tracing down */
    edgeEnd = false;
    colShift *= -1;
    rowShift *= -1;
    if (colShift &lt; 0) {
        if (col &gt; 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col &lt; W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;
    if (rowShift &lt; 0) {
        if (row &gt; 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row &lt; H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
    i = (unsigned long)(newRow*3*W + 3*newCol);
    while ((edgeDir[newRow][newCol] == dir) &amp;&amp; !edgeEnd &amp;&amp; (*(m_destinationBmp + i) == 255)) {
        if (colShift &lt; 0) {
            if (newCol &gt; 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol &lt; W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift &lt; 0) {
            if (newRow &gt; 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow &lt; H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
        nonMax[pixelCount][0] = newRow;
        nonMax[pixelCount][1] = newCol;
        nonMax[pixelCount][2] = gradient[newRow][newCol];
        pixelCount++;
        i = (unsigned long)(newRow*3*W + 3*newCol);
    }
 
    /* Suppress non-maximum edges */
    max[0] = 0;
    max[1] = 0;
    max[2] = 0;
    for (count = 0; count &lt; pixelCount; count++) {
        if (nonMax[count][2] &gt; max[2]) {
            max[0] = nonMax[count][0];
            max[1] = nonMax[count][1];
            max[2] = nonMax[count][2];
        }
    }
    for (count = 0; count &lt; pixelCount; count++) {
        i = (unsigned long)(nonMax[count][0]*3*W + 3*nonMax[count][1]);
        *(m_destinationBmp + i) =
        *(m_destinationBmp + i + 1) =
        *(m_destinationBmp + i + 2) = 0;
    }
}

 

دانلود کد فوق از طریق لینک زیر:

Canny in C++ -No2

رمز فایل : behsanandish.com

الگوریتم Canny در سی پلاس پلاس قسمت 1
الگوریتم Canny در سی پلاس پلاس قسمت 2
الگوریتم Canny در سی پلاس پلاس قسمت 3
الگوریتم Canny در سی پلاس پلاس قسمت 4

 

مرحله 3: ردیابی در امتداد لبه ها

گام بعدی در واقع این است که در امتداد لبه ها بر اساس نقاط قوت و جهت های لبه که قبلا محاسبه شده است ردیابی شود. هر پیکسل از طریق استفاده از دو تودرتو برای حلقه ها چرخه می زند. اگر پیکسل فعلی دارای قدرت شیب بیشتر از مقدار upperThreshold تعریف شده باشد، یک سوئیچ اجرا می شود. این سوئیچ توسط جهت لبه پیکسل فعلی تعیین می شود. این ردیف و ستون، پیکسل ممکن بعدی را در این جهت ذخیره می کند و سپس جهت لبه و استحکام شیب آن پیکسل را آزمایش می کند. اگر آن همان جهت لبه و  قدرت گرادیان بزرگتر از lowerThreshold را دارد، آن پیکسل به سفید و پیکسل بعدی در امتداد آن لبه آزمایش می شود. به این ترتیب هر لبه قابل توجه تیز تشخیص داده شده و به سفید تنظیم می شود در حالیکه تمام پیکسل های دیگر به سیاه تنظیم می شود.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
#include "stdafx.h"
#include "tripod.h"
#include "tripodDlg.h"
 
#include "LVServerDefs.h"
#include "math.h"
#include &lt;fstream&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
 
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
using namespace std;
 
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
 
class CAboutDlg : public CDialog
{
public:
    CAboutDlg();
 
// Dialog Data
    //{{AFX_DATA(CAboutDlg)
    enum { IDD = IDD_ABOUTBOX };
    //}}AFX_DATA
 
    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CAboutDlg)
    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
    //}}AFX_VIRTUAL
 
// Implementation
protected:
    //{{AFX_MSG(CAboutDlg)
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()
};
 
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
    //{{AFX_DATA_INIT(CAboutDlg)
    //}}AFX_DATA_INIT
}
 
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CAboutDlg)
    //}}AFX_DATA_MAP
}
 
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
    //{{AFX_MSG_MAP(CAboutDlg)
        // No message handlers
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/////////////////////////////////////////////////////////////////////////////
// CTripodDlg dialog
 
CTripodDlg::CTripodDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CTripodDlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CTripodDlg)
        // NOTE: the ClassWizard will add member initialization here
    //}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    m_hIcon = AfxGetApp()-&gt;LoadIcon(IDR_MAINFRAME);
 
    //////////////// Set destination BMP to NULL first
    m_destinationBitmapInfoHeader = NULL;
 
}
 
////////////////////// Additional generic functions
 
static unsigned PixelBytes(int w, int bpp)
{
    return (w * bpp + 7) / 8;
}
 
static unsigned DibRowSize(int w, int bpp)
{
    return (w * bpp + 31) / 32 * 4;
}
 
static unsigned DibRowSize(LPBITMAPINFOHEADER pbi)
{
    return DibRowSize(pbi-&gt;biWidth, pbi-&gt;biBitCount);
}
 
static unsigned DibRowPadding(int w, int bpp)
{
    return DibRowSize(w, bpp) - PixelBytes(w, bpp);
}
 
static unsigned DibRowPadding(LPBITMAPINFOHEADER pbi)
{
    return DibRowPadding(pbi-&gt;biWidth, pbi-&gt;biBitCount);
}
 
static unsigned DibImageSize(int w, int h, int bpp)
{
    return h * DibRowSize(w, bpp);
}
 
static size_t DibSize(int w, int h, int bpp)
{
    return sizeof (BITMAPINFOHEADER) + DibImageSize(w, h, bpp);
}
 
/////////////////////// end of generic functions
 
 
void CTripodDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CTripodDlg)
    DDX_Control(pDX, IDC_PROCESSEDVIEW, m_cVideoProcessedView);
    DDX_Control(pDX, IDC_UNPROCESSEDVIEW, m_cVideoUnprocessedView);
    //}}AFX_DATA_MAP
}
 
BEGIN_MESSAGE_MAP(CTripodDlg, CDialog)
    //{{AFX_MSG_MAP(CTripodDlg)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_BN_CLICKED(IDEXIT, OnExit)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/////////////////////////////////////////////////////////////////////////////
// CTripodDlg message handlers
 
BOOL CTripodDlg::OnInitDialog()
{
    CDialog::OnInitDialog();
 
    // Add "About..." menu item to system menu.
 
    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX &amp; 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX &lt; 0xF000);
 
    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        CString strAboutMenu;
        strAboutMenu.LoadString(IDS_ABOUTBOX);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu-&gt;AppendMenu(MF_SEPARATOR);
            pSysMenu-&gt;AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }
 
    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon
     
    // TODO: Add extra initialization here
 
    // For Unprocessed view videoportal (top one)
    char sRegUnprocessedView[] = "HKEY_LOCAL_MACHINE\\Software\\UnprocessedView";
    m_cVideoUnprocessedView.PrepareControl("UnprocessedView", sRegUnprocessedView, 0 );
    m_cVideoUnprocessedView.EnableUIElements(UIELEMENT_STATUSBAR,0,TRUE);
    m_cVideoUnprocessedView.ConnectCamera2();
    m_cVideoUnprocessedView.SetEnablePreview(TRUE);
 
    // For binary view videoportal (bottom one)
    char sRegProcessedView[] = "HKEY_LOCAL_MACHINE\\Software\\ProcessedView";
    m_cVideoProcessedView.PrepareControl("ProcessedView", sRegProcessedView, 0 );  
    m_cVideoProcessedView.EnableUIElements(UIELEMENT_STATUSBAR,0,TRUE);
    m_cVideoProcessedView.ConnectCamera2();
    m_cVideoProcessedView.SetEnablePreview(TRUE);
 
    // Initialize the size of binary videoportal
    m_cVideoProcessedView.SetPreviewMaxHeight(240);
    m_cVideoProcessedView.SetPreviewMaxWidth(320);
 
    // Uncomment if you wish to fix the live videoportal's size
    // m_cVideoUnprocessedView.SetPreviewMaxHeight(240);
    // m_cVideoUnprocessedView.SetPreviewMaxWidth(320);
 
    // Find the screen coodinates of the binary videoportal
    m_cVideoProcessedView.GetWindowRect(m_rectForProcessedView);
    ScreenToClient(m_rectForProcessedView);
    allocateDib(CSize(320, 240));
 
    // Start grabbing frame data for Procssed videoportal (bottom one)
    m_cVideoProcessedView.StartVideoHook(0);
 
    return TRUE;  // return TRUE  unless you set the focus to a control
}
 
void CTripodDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID &amp; 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        dlgAbout.DoModal();
    }
    else
    {
        CDialog::OnSysCommand(nID, lParam);
    }
}
 
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.
 
void CTripodDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting
 
        SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
 
        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&amp;rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
 
        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}
 
// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTripodDlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}
 
void CTripodDlg::OnExit()
{
    // TODO: Add your control notification handler code here
 
    // Kill live view videoportal (top one)
    m_cVideoUnprocessedView.StopVideoHook(0);
    m_cVideoUnprocessedView.DisconnectCamera();
     
    // Kill binary view videoportal (bottom one)
    m_cVideoProcessedView.StopVideoHook(0);
    m_cVideoProcessedView.DisconnectCamera();  
 
    // Kill program
    DestroyWindow();   
 
     
 
}
 
BEGIN_EVENTSINK_MAP(CTripodDlg, CDialog)
    //{{AFX_EVENTSINK_MAP(CTripodDlg)
    ON_EVENT(CTripodDlg, IDC_PROCESSEDVIEW, 1 /* PortalNotification */, OnPortalNotificationProcessedview, VTS_I4 VTS_I4 VTS_I4 VTS_I4)
    //}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()
 
void CTripodDlg::OnPortalNotificationProcessedview(long lMsg, long lParam1, long lParam2, long lParam3)
{
    // TODO: Add your control notification handler code here
     
    // This function is called at the camera's frame rate
     
#define NOTIFICATIONMSG_VIDEOHOOK   10
 
    // Declare some useful variables
    // QCSDKMFC.pdf (Quickcam MFC documentation) p. 103 explains the variables lParam1, lParam2, lParam3 too
     
    LPBITMAPINFOHEADER lpBitmapInfoHeader; // Frame's info header contains info like width and height
    LPBYTE lpBitmapPixelData; // This pointer-to-long will point to the start of the frame's pixel data
    unsigned long lTimeStamp; // Time when frame was grabbed
 
    switch(lMsg) {
        case NOTIFICATIONMSG_VIDEOHOOK:
            {
                lpBitmapInfoHeader = (LPBITMAPINFOHEADER) lParam1;
                lpBitmapPixelData = (LPBYTE) lParam2;
                lTimeStamp = (unsigned long) lParam3;
 
                grayScaleTheFrameData(lpBitmapInfoHeader, lpBitmapPixelData);
                doMyImageProcessing(lpBitmapInfoHeader); // Place where you'd add your image processing code
                displayMyResults(lpBitmapInfoHeader);
 
            }
            break;
 
        default:
            break;
    }  
}
 
void CTripodDlg::allocateDib(CSize sz)
{
    // Purpose: allocate information for a device independent bitmap (DIB)
    // Called from OnInitVideo
 
    if(m_destinationBitmapInfoHeader) {
        free(m_destinationBitmapInfoHeader);
        m_destinationBitmapInfoHeader = NULL;
    }
 
    if(sz.cx | sz.cy) {
        m_destinationBitmapInfoHeader = (LPBITMAPINFOHEADER)malloc(DibSize(sz.cx, sz.cy, 24));
        ASSERT(m_destinationBitmapInfoHeader);
        m_destinationBitmapInfoHeader-&gt;biSize = sizeof(BITMAPINFOHEADER);
        m_destinationBitmapInfoHeader-&gt;biWidth = sz.cx;
        m_destinationBitmapInfoHeader-&gt;biHeight = sz.cy;
        m_destinationBitmapInfoHeader-&gt;biPlanes = 1;
        m_destinationBitmapInfoHeader-&gt;biBitCount = 24;
        m_destinationBitmapInfoHeader-&gt;biCompression = 0;
        m_destinationBitmapInfoHeader-&gt;biSizeImage = DibImageSize(sz.cx, sz.cy, 24);
        m_destinationBitmapInfoHeader-&gt;biXPelsPerMeter = 0;
        m_destinationBitmapInfoHeader-&gt;biYPelsPerMeter = 0;
        m_destinationBitmapInfoHeader-&gt;biClrImportant = 0;
        m_destinationBitmapInfoHeader-&gt;biClrUsed = 0;
    }
}
 
void CTripodDlg::displayMyResults(LPBITMAPINFOHEADER lpThisBitmapInfoHeader)
{
    // displayMyResults: Displays results of doMyImageProcessing() in the videoport
    // Notes: StretchDIBits stretches a device-independent bitmap to the appropriate size
 
    CDC             *pDC;   // Device context to display bitmap data
     
    pDC = GetDC(); 
    int nOldMode = SetStretchBltMode(pDC-&gt;GetSafeHdc(),COLORONCOLOR);
 
    StretchDIBits(
        pDC-&gt;GetSafeHdc(),
        m_rectForProcessedView.left,                // videoportal left-most coordinate
        m_rectForProcessedView.top,                 // videoportal top-most coordinate
        m_rectForProcessedView.Width(),             // videoportal width
        m_rectForProcessedView.Height(),            // videoportal height
        0,                                          // Row position to display bitmap in videoportal
        0,                                          // Col position to display bitmap in videoportal
        lpThisBitmapInfoHeader-&gt;biWidth,         // m_destinationBmp's number of columns
        lpThisBitmapInfoHeader-&gt;biHeight,            // m_destinationBmp's number of rows
        m_destinationBmp,                           // The bitmap to display; use the one resulting from doMyImageProcessing
        (BITMAPINFO*)m_destinationBitmapInfoHeader, // The bitmap's header info e.g. width, height, number of bits etc
        DIB_RGB_COLORS,                             // Use default 24-bit color table
        SRCCOPY                                     // Just display
    );
  
    SetStretchBltMode(pDC-&gt;GetSafeHdc(),nOldMode);
 
    ReleaseDC(pDC);
 
    // Note: 04/24/02 - Added the following:
    // Christopher Wagner cwagner@fas.harvard.edu noticed that memory wasn't being freed
 
    // Recall OnPortalNotificationProcessedview, which gets called everytime
    // a frame of data arrives, performs 3 steps:
    // (1) grayScaleTheFrameData - which mallocs m_destinationBmp
    // (2) doMyImageProcesing
    // (3) displayMyResults - which we're in now
    // Since we're finished with the memory we malloc'ed for m_destinationBmp
    // we should free it:
     
    free(m_destinationBmp);
 
    // End of adds
}
 
void CTripodDlg::grayScaleTheFrameData(LPBITMAPINFOHEADER lpThisBitmapInfoHeader, LPBYTE lpThisBitmapPixelData)
{
 
    // grayScaleTheFrameData: Called by CTripodDlg::OnPortalNotificationBinaryview
    // Task: Read current frame pixel data and computes a grayscale version
 
    unsigned int    W, H;             // Width and Height of current frame [pixels]
    BYTE            *sourceBmp;       // Pointer to current frame of data
    unsigned int    row, col;
    unsigned long   i;
    BYTE            grayValue;
 
    BYTE            redValue;
    BYTE            greenValue;
    BYTE            blueValue;
 
    W = lpThisBitmapInfoHeader-&gt;biWidth;  // biWidth: number of columns
    H = lpThisBitmapInfoHeader-&gt;biHeight; // biHeight: number of rows
 
    // Store pixel data in row-column vector format
    // Recall that each pixel requires 3 bytes (red, blue and green bytes)
    // m_destinationBmp is a protected member and declared in binarizeDlg.h
 
    m_destinationBmp = (BYTE*)malloc(H*3*W*sizeof(BYTE));
 
    // Point to the current frame's pixel data
    sourceBmp = lpThisBitmapPixelData;
 
    for (row = 0; row &lt; H; row++) {
        for (col = 0; col &lt; W; col++) {
 
            // Recall each pixel is composed of 3 bytes
            i = (unsigned long)(row*3*W + 3*col);
         
            // The source pixel has a blue, green andred value:
            blueValue  = *(sourceBmp + i);
            greenValue = *(sourceBmp + i + 1);
            redValue   = *(sourceBmp + i + 2);
 
            // A standard equation for computing a grayscale value based on RGB values
            grayValue = (BYTE)(0.299*redValue + 0.587*greenValue + 0.114*blueValue);
 
            // The destination BMP will be a grayscale version of the source BMP
            *(m_destinationBmp + i)     = grayValue;
            *(m_destinationBmp + i + 1) = grayValue;
            *(m_destinationBmp + i + 2) = grayValue;
             
        }
    }
}
 
 
void CTripodDlg::doMyImageProcessing(LPBITMAPINFOHEADER lpThisBitmapInfoHeader)
{
    // doMyImageProcessing:  This is where you'd write your own image processing code
    // Task: Read a pixel's grayscale value and process accordingly
 
    unsigned int    W, H;           // Width and Height of current frame [pixels]
    unsigned int    row, col;       // Pixel's row and col positions
    unsigned long   i;              // Dummy variable for row-column vector
    int     upperThreshold = 60;    // Gradient strength nessicary to start edge
    int     lowerThreshold = 30;    // Minimum gradient strength to continue edge
    unsigned long iOffset;          // Variable to offset row-column vector during sobel mask
    int rowOffset;                  // Row offset from the current pixel
    int colOffset;                  // Col offset from the current pixel
    int rowTotal = 0;               // Row position of offset pixel
    int colTotal = 0;               // Col position of offset pixel
    int Gx;                         // Sum of Sobel mask products values in the x direction
    int Gy;                         // Sum of Sobel mask products values in the y direction
    float thisAngle;                // Gradient direction based on Gx and Gy
    int newAngle;                   // Approximation of the gradient direction
    bool edgeEnd;                   // Stores whether or not the edge is at the edge of the possible image
    int GxMask[3][3];               // Sobel mask in the x direction
    int GyMask[3][3];               // Sobel mask in the y direction
    int newPixel;                   // Sum pixel values for gaussian
    int gaussianMask[5][5];         // Gaussian mask
 
    W = lpThisBitmapInfoHeader-&gt;biWidth;  // biWidth: number of columns
    H = lpThisBitmapInfoHeader-&gt;biHeight; // biHeight: number of rows
     
    for (row = 0; row &lt; H; row++) {
        for (col = 0; col &lt; W; col++) {
            edgeDir[row][col] = 0;
        }
    }
 
    /* Declare Sobel masks */
    GxMask[0][0] = -1; GxMask[0][1] = 0; GxMask[0][2] = 1;
    GxMask[1][0] = -2; GxMask[1][1] = 0; GxMask[1][2] = 2;
    GxMask[2][0] = -1; GxMask[2][1] = 0; GxMask[2][2] = 1;
     
    GyMask[0][0] =  1; GyMask[0][1] =  2; GyMask[0][2] =  1;
    GyMask[1][0] =  0; GyMask[1][1] =  0; GyMask[1][2] =  0;
    GyMask[2][0] = -1; GyMask[2][1] = -2; GyMask[2][2] = -1;
 
    /* Declare Gaussian mask */
    gaussianMask[0][0] = 2;     gaussianMask[0][1] = 4;     gaussianMask[0][2] = 5;     gaussianMask[0][3] = 4;     gaussianMask[0][4] = 2;
    gaussianMask[1][0] = 4;     gaussianMask[1][1] = 9;     gaussianMask[1][2] = 12;    gaussianMask[1][3] = 9;     gaussianMask[1][4] = 4;
    gaussianMask[2][0] = 5;     gaussianMask[2][1] = 12;    gaussianMask[2][2] = 15;    gaussianMask[2][3] = 12;    gaussianMask[2][4] = 2;
    gaussianMask[3][0] = 4;     gaussianMask[3][1] = 9;     gaussianMask[3][2] = 12;    gaussianMask[3][3] = 9;     gaussianMask[3][4] = 4;
    gaussianMask[4][0] = 2;     gaussianMask[4][1] = 4;     gaussianMask[4][2] = 5;     gaussianMask[4][3] = 4;     gaussianMask[4][4] = 2;
     
 
    /* Gaussian Blur */
    for (row = 2; row &lt; H-2; row++) {
        for (col = 2; col &lt; W-2; col++) {
            newPixel = 0;
            for (rowOffset=-2; rowOffset&lt;=2; rowOffset++) {
                for (colOffset=-2; colOffset&lt;=2; colOffset++) {
                    rowTotal = row + rowOffset;
                    colTotal = col + colOffset;
                    iOffset = (unsigned long)(rowTotal*3*W + colTotal*3);
                    newPixel += (*(m_destinationBmp + iOffset)) * gaussianMask[2 + rowOffset][2 + colOffset];
                }
            }
            i = (unsigned long)(row*3*W + col*3);
            *(m_destinationBmp + i) = newPixel / 159;
        }
    }
 
    /* Determine edge directions and gradient strengths */
    for (row = 1; row &lt; H-1; row++) {
        for (col = 1; col &lt; W-1; col++) {
            i = (unsigned long)(row*3*W + 3*col);
            Gx = 0;
            Gy = 0;
            /* Calculate the sum of the Sobel mask times the nine surrounding pixels in the x and y direction */
            for (rowOffset=-1; rowOffset&lt;=1; rowOffset++) {
                for (colOffset=-1; colOffset&lt;=1; colOffset++) {
                    rowTotal = row + rowOffset;
                    colTotal = col + colOffset;
                    iOffset = (unsigned long)(rowTotal*3*W + colTotal*3);
                    Gx = Gx + (*(m_destinationBmp + iOffset) * GxMask[rowOffset + 1][colOffset + 1]);
                    Gy = Gy + (*(m_destinationBmp + iOffset) * GyMask[rowOffset + 1][colOffset + 1]);
                }
            }
 
            gradient[row][col] = sqrt(pow(Gx,2.0) + pow(Gy,2.0));   // Calculate gradient strength         
            thisAngle = (atan2(Gx,Gy)/3.14159) * 180.0;     // Calculate actual direction of edge
             
            /* Convert actual edge direction to approximate value */
            if ( ( (thisAngle &lt; 22.5) &amp;&amp; (thisAngle &gt; -22.5) ) || (thisAngle &gt; 157.5) || (thisAngle &lt; -157.5) )
                newAngle = 0;
            if ( ( (thisAngle &gt; 22.5) &amp;&amp; (thisAngle &lt; 67.5) ) || ( (thisAngle &lt; -112.5) &amp;&amp; (thisAngle &gt; -157.5) ) )
                newAngle = 45;
            if ( ( (thisAngle &gt; 67.5) &amp;&amp; (thisAngle &lt; 112.5) ) || ( (thisAngle &lt; -67.5) &amp;&amp; (thisAngle &gt; -112.5) ) )
                newAngle = 90;
            if ( ( (thisAngle &gt; 112.5) &amp;&amp; (thisAngle &lt; 157.5) ) || ( (thisAngle &lt; -22.5) &amp;&amp; (thisAngle &gt; -67.5) ) )
                newAngle = 135;
                 
            edgeDir[row][col] = newAngle;       // Store the approximate edge direction of each pixel in one array
        }
    }
 
    /* Trace along all the edges in the image */
    for (row = 1; row &lt; H - 1; row++) {
        for (col = 1; col &lt; W - 1; col++) {
            edgeEnd = false;
            if (gradient[row][col] &gt; upperThreshold) {       // Check to see if current pixel has a high enough gradient strength to be part of an edge
                /* Switch based on current pixel's edge direction */
                switch (edgeDir[row][col]){    
                    case 0:
                        findEdge(0, 1, row, col, 0, lowerThreshold);
                        break;
                    case 45:
                        findEdge(1, 1, row, col, 45, lowerThreshold);
                        break;
                    case 90:
                        findEdge(1, 0, row, col, 90, lowerThreshold);
                        break;
                    case 135:
                        findEdge(1, -1, row, col, 135, lowerThreshold);
                        break;
                    default :
                        i = (unsigned long)(row*3*W + 3*col);
                        *(m_destinationBmp + i) =
                        *(m_destinationBmp + i + 1) =
                        *(m_destinationBmp + i + 2) = 0;
                        break;
                    }
                }
            else {
                i = (unsigned long)(row*3*W + 3*col);
                    *(m_destinationBmp + i) =
                    *(m_destinationBmp + i + 1) =
                    *(m_destinationBmp + i + 2) = 0;
            }  
        }
    }
     
    /* Suppress any pixels not changed by the edge tracing */
    for (row = 0; row &lt; H; row++) {
        for (col = 0; col &lt; W; col++) { 
            // Recall each pixel is composed of 3 bytes
            i = (unsigned long)(row*3*W + 3*col);
            // If a pixel's grayValue is not black or white make it black
            if( ((*(m_destinationBmp + i) != 255) &amp;&amp; (*(m_destinationBmp + i) != 0)) || ((*(m_destinationBmp + i + 1) != 255) &amp;&amp; (*(m_destinationBmp + i + 1) != 0)) || ((*(m_destinationBmp + i + 2) != 255) &amp;&amp; (*(m_destinationBmp + i + 2) != 0)) )
                *(m_destinationBmp + i) =
                *(m_destinationBmp + i + 1) =
                *(m_destinationBmp + i + 2) = 0; // Make pixel black
        }
    }
 
    /* Non-maximum Suppression */
    for (row = 1; row &lt; H - 1; row++) {
        for (col = 1; col &lt; W - 1; col++) {
            i = (unsigned long)(row*3*W + 3*col);
            if (*(m_destinationBmp + i) == 255) {       // Check to see if current pixel is an edge
                /* Switch based on current pixel's edge direction */
                switch (edgeDir[row][col]) {       
                    case 0:
                        suppressNonMax( 1, 0, row, col, 0, lowerThreshold);
                        break;
                    case 45:
                        suppressNonMax( 1, -1, row, col, 45, lowerThreshold);
                        break;
                    case 90:
                        suppressNonMax( 0, 1, row, col, 90, lowerThreshold);
                        break;
                    case 135:
                        suppressNonMax( 1, 1, row, col, 135, lowerThreshold);
                        break;
                    default :
                        break;
                }
            }  
        }
    }
     
}
 
void CTripodDlg::findEdge(int rowShift, int colShift, int row, int col, int dir, int lowerThreshold)
{
    int W = 320;
    int H = 240;
    int newRow;
    int newCol;
    unsigned long i;
    bool edgeEnd = false;
 
    /* Find the row and column values for the next possible pixel on the edge */
    if (colShift &lt; 0) {
        if (col &gt; 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col &lt; W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;     // If the next pixel would be off image, don't do the while loop
    if (rowShift &lt; 0) {
        if (row &gt; 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row &lt; H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
         
    /* Determine edge directions and gradient strengths */
    while ( (edgeDir[newRow][newCol]==dir) &amp;&amp; !edgeEnd &amp;&amp; (gradient[newRow][newCol] &gt; lowerThreshold) ) {
        /* Set the new pixel as white to show it is an edge */
        i = (unsigned long)(newRow*3*W + 3*newCol);
        *(m_destinationBmp + i) =
        *(m_destinationBmp + i + 1) =
        *(m_destinationBmp + i + 2) = 255;
        if (colShift &lt; 0) {
            if (newCol &gt; 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol &lt; W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift &lt; 0) {
            if (newRow &gt; 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow &lt; H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
    }  
}
 
void CTripodDlg::suppressNonMax(int rowShift, int colShift, int row, int col, int dir, int lowerThreshold)
{
    int W = 320;
    int H = 240;
    int newRow = 0;
    int newCol = 0;
    unsigned long i;
    bool edgeEnd = false;
    float nonMax[320][3];           // Temporarily stores gradients and positions of pixels in parallel edges
    int pixelCount = 0;                 // Stores the number of pixels in parallel edges
    int count;                      // A for loop counter
    int max[3];                     // Maximum point in a wide edge
     
    if (colShift &lt; 0) {
        if (col &gt; 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col &lt; W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;     // If the next pixel would be off image, don't do the while loop
    if (rowShift &lt; 0) {
        if (row &gt; 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row &lt; H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
    i = (unsigned long)(newRow*3*W + 3*newCol);
    /* Find non-maximum parallel edges tracing up */
    while ((edgeDir[newRow][newCol] == dir) &amp;&amp; !edgeEnd &amp;&amp; (*(m_destinationBmp + i) == 255)) {
        if (colShift &lt; 0) {
            if (newCol &gt; 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol &lt; W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift &lt; 0) {
            if (newRow &gt; 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow &lt; H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
        nonMax[pixelCount][0] = newRow;
        nonMax[pixelCount][1] = newCol;
        nonMax[pixelCount][2] = gradient[newRow][newCol];
        pixelCount++;
        i = (unsigned long)(newRow*3*W + 3*newCol);
    }
 
    /* Find non-maximum parallel edges tracing down */
    edgeEnd = false;
    colShift *= -1;
    rowShift *= -1;
    if (colShift &lt; 0) {
        if (col &gt; 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col &lt; W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;
    if (rowShift &lt; 0) {
        if (row &gt; 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row &lt; H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
    i = (unsigned long)(newRow*3*W + 3*newCol);
    while ((edgeDir[newRow][newCol] == dir) &amp;&amp; !edgeEnd &amp;&amp; (*(m_destinationBmp + i) == 255)) {
        if (colShift &lt; 0) {
            if (newCol &gt; 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol &lt; W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift &lt; 0) {
            if (newRow &gt; 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow &lt; H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
        nonMax[pixelCount][0] = newRow;
        nonMax[pixelCount][1] = newCol;
        nonMax[pixelCount][2] = gradient[newRow][newCol];
        pixelCount++;
        i = (unsigned long)(newRow*3*W + 3*newCol);
    }
 
    /* Suppress non-maximum edges */
    max[0] = 0;
    max[1] = 0;
    max[2] = 0;
    for (count = 0; count &lt; pixelCount; count++) {
        if (nonMax[count][2] &gt; max[2]) {
            max[0] = nonMax[count][0];
            max[1] = nonMax[count][1];
            max[2] = nonMax[count][2];
        }
    }
    for (count = 0; count &lt; pixelCount; count++) {
        i = (unsigned long)(nonMax[count][0]*3*W + 3*nonMax[count][1]);
        *(m_destinationBmp + i) =
        *(m_destinationBmp + i + 1) =
        *(m_destinationBmp + i + 2) = 0;
    }
}

الگوریتم Canny در سی پلاس پلاس قسمت 1
الگوریتم Canny در سی پلاس پلاس قسمت 2
الگوریتم Canny در سی پلاس پلاس قسمت 3
الگوریتم Canny در سی پلاس پلاس قسمت 4

مرحله 2: پیدا کردن قدرت و جهت گرادیان لبه.

گام بعدی استفاده از Mask های Sobel برای پیدا کردن قدرت و جهت گرادیان لبه برای هر پیکسل است. ابتدا ماسک های Sobel به محدوده پیکسل 3×3 پیکسل فعلی در هر دو جهت x و y اعمال می شود. سپس مجموع مقدار هر ماسک ضربدر پیکسل مربوطه به ترتیب به عنوان مقادیر Gx و Gy محاسبه می شود. ریشه دوم مربع Gx به اضافه Gy مربع برابر قدرت لبه است. Tangent معکوس Gx / Gy جهت لبه را تولید می کند. سپس جهت لبه تقریب شده است به یکی از چهار مقادیر ممکن که ایجاد می کند جهت های ممکن را که  یک لبه می تواند در یک تصویر از یک شبکه پیکسل مربع باشد. این جهت لبه در edgeDir [row] [col] ذخیره می شود و قدرت گرادیان در  array gradient[row] [col] ذخیره می شود.

 

CannyEdgeWeel

هر زاویه لبه در 11.25 درجه از یکی از  زاویه های ممکن به آن مقدار تغییر می کند.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
#include "stdafx.h"
#include "tripod.h"
#include "tripodDlg.h"
 
#include "LVServerDefs.h"
#include "math.h"
#include &lt;fstream&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
 
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
using namespace std;
 
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
 
class CAboutDlg : public CDialog
{
public:
    CAboutDlg();
 
// Dialog Data
    //{{AFX_DATA(CAboutDlg)
    enum { IDD = IDD_ABOUTBOX };
    //}}AFX_DATA
 
    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CAboutDlg)
    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
    //}}AFX_VIRTUAL
 
// Implementation
protected:
    //{{AFX_MSG(CAboutDlg)
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()
};
 
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
    //{{AFX_DATA_INIT(CAboutDlg)
    //}}AFX_DATA_INIT
}
 
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CAboutDlg)
    //}}AFX_DATA_MAP
}
 
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
    //{{AFX_MSG_MAP(CAboutDlg)
        // No message handlers
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/////////////////////////////////////////////////////////////////////////////
// CTripodDlg dialog
 
CTripodDlg::CTripodDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CTripodDlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CTripodDlg)
        // NOTE: the ClassWizard will add member initialization here
    //}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    m_hIcon = AfxGetApp()-&gt;LoadIcon(IDR_MAINFRAME);
 
    //////////////// Set destination BMP to NULL first
    m_destinationBitmapInfoHeader = NULL;
 
}
 
////////////////////// Additional generic functions
 
static unsigned PixelBytes(int w, int bpp)
{
    return (w * bpp + 7) / 8;
}
 
static unsigned DibRowSize(int w, int bpp)
{
    return (w * bpp + 31) / 32 * 4;
}
 
static unsigned DibRowSize(LPBITMAPINFOHEADER pbi)
{
    return DibRowSize(pbi-&gt;biWidth, pbi-&gt;biBitCount);
}
 
static unsigned DibRowPadding(int w, int bpp)
{
    return DibRowSize(w, bpp) - PixelBytes(w, bpp);
}
 
static unsigned DibRowPadding(LPBITMAPINFOHEADER pbi)
{
    return DibRowPadding(pbi-&gt;biWidth, pbi-&gt;biBitCount);
}
 
static unsigned DibImageSize(int w, int h, int bpp)
{
    return h * DibRowSize(w, bpp);
}
 
static size_t DibSize(int w, int h, int bpp)
{
    return sizeof (BITMAPINFOHEADER) + DibImageSize(w, h, bpp);
}
 
/////////////////////// end of generic functions
 
 
void CTripodDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CTripodDlg)
    DDX_Control(pDX, IDC_PROCESSEDVIEW, m_cVideoProcessedView);
    DDX_Control(pDX, IDC_UNPROCESSEDVIEW, m_cVideoUnprocessedView);
    //}}AFX_DATA_MAP
}
 
BEGIN_MESSAGE_MAP(CTripodDlg, CDialog)
    //{{AFX_MSG_MAP(CTripodDlg)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_BN_CLICKED(IDEXIT, OnExit)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/////////////////////////////////////////////////////////////////////////////
// CTripodDlg message handlers
 
BOOL CTripodDlg::OnInitDialog()
{
    CDialog::OnInitDialog();
 
    // Add "About..." menu item to system menu.
 
    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX &amp; 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX &lt; 0xF000);
 
    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        CString strAboutMenu;
        strAboutMenu.LoadString(IDS_ABOUTBOX);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu-&gt;AppendMenu(MF_SEPARATOR);
            pSysMenu-&gt;AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }
 
    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon
     
    // TODO: Add extra initialization here
 
    // For Unprocessed view videoportal (top one)
    char sRegUnprocessedView[] = "HKEY_LOCAL_MACHINE\\Software\\UnprocessedView";
    m_cVideoUnprocessedView.PrepareControl("UnprocessedView", sRegUnprocessedView, 0 );
    m_cVideoUnprocessedView.EnableUIElements(UIELEMENT_STATUSBAR,0,TRUE);
    m_cVideoUnprocessedView.ConnectCamera2();
    m_cVideoUnprocessedView.SetEnablePreview(TRUE);
 
    // For binary view videoportal (bottom one)
    char sRegProcessedView[] = "HKEY_LOCAL_MACHINE\\Software\\ProcessedView";
    m_cVideoProcessedView.PrepareControl("ProcessedView", sRegProcessedView, 0 );  
    m_cVideoProcessedView.EnableUIElements(UIELEMENT_STATUSBAR,0,TRUE);
    m_cVideoProcessedView.ConnectCamera2();
    m_cVideoProcessedView.SetEnablePreview(TRUE);
 
    // Initialize the size of binary videoportal
    m_cVideoProcessedView.SetPreviewMaxHeight(240);
    m_cVideoProcessedView.SetPreviewMaxWidth(320);
 
    // Uncomment if you wish to fix the live videoportal's size
    // m_cVideoUnprocessedView.SetPreviewMaxHeight(240);
    // m_cVideoUnprocessedView.SetPreviewMaxWidth(320);
 
    // Find the screen coodinates of the binary videoportal
    m_cVideoProcessedView.GetWindowRect(m_rectForProcessedView);
    ScreenToClient(m_rectForProcessedView);
    allocateDib(CSize(320, 240));
 
    // Start grabbing frame data for Procssed videoportal (bottom one)
    m_cVideoProcessedView.StartVideoHook(0);
 
    return TRUE;  // return TRUE  unless you set the focus to a control
}
 
void CTripodDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID &amp; 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        dlgAbout.DoModal();
    }
    else
    {
        CDialog::OnSysCommand(nID, lParam);
    }
}
 
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.
 
void CTripodDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting
 
        SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
 
        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&amp;rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
 
        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}
 
// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTripodDlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}
 
void CTripodDlg::OnExit()
{
    // TODO: Add your control notification handler code here
 
    // Kill live view videoportal (top one)
    m_cVideoUnprocessedView.StopVideoHook(0);
    m_cVideoUnprocessedView.DisconnectCamera();
     
    // Kill binary view videoportal (bottom one)
    m_cVideoProcessedView.StopVideoHook(0);
    m_cVideoProcessedView.DisconnectCamera();  
 
    // Kill program
    DestroyWindow();   
 
     
 
}
 
BEGIN_EVENTSINK_MAP(CTripodDlg, CDialog)
    //{{AFX_EVENTSINK_MAP(CTripodDlg)
    ON_EVENT(CTripodDlg, IDC_PROCESSEDVIEW, 1 /* PortalNotification */, OnPortalNotificationProcessedview, VTS_I4 VTS_I4 VTS_I4 VTS_I4)
    //}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()
 
void CTripodDlg::OnPortalNotificationProcessedview(long lMsg, long lParam1, long lParam2, long lParam3)
{
    // TODO: Add your control notification handler code here
     
    // This function is called at the camera's frame rate
     
#define NOTIFICATIONMSG_VIDEOHOOK   10
 
    // Declare some useful variables
    // QCSDKMFC.pdf (Quickcam MFC documentation) p. 103 explains the variables lParam1, lParam2, lParam3 too
     
    LPBITMAPINFOHEADER lpBitmapInfoHeader; // Frame's info header contains info like width and height
    LPBYTE lpBitmapPixelData; // This pointer-to-long will point to the start of the frame's pixel data
    unsigned long lTimeStamp; // Time when frame was grabbed
 
    switch(lMsg) {
        case NOTIFICATIONMSG_VIDEOHOOK:
            {
                lpBitmapInfoHeader = (LPBITMAPINFOHEADER) lParam1;
                lpBitmapPixelData = (LPBYTE) lParam2;
                lTimeStamp = (unsigned long) lParam3;
 
                grayScaleTheFrameData(lpBitmapInfoHeader, lpBitmapPixelData);
                doMyImageProcessing(lpBitmapInfoHeader); // Place where you'd add your image processing code
                displayMyResults(lpBitmapInfoHeader);
 
            }
            break;
 
        default:
            break;
    }  
}
 
void CTripodDlg::allocateDib(CSize sz)
{
    // Purpose: allocate information for a device independent bitmap (DIB)
    // Called from OnInitVideo
 
    if(m_destinationBitmapInfoHeader) {
        free(m_destinationBitmapInfoHeader);
        m_destinationBitmapInfoHeader = NULL;
    }
 
    if(sz.cx | sz.cy) {
        m_destinationBitmapInfoHeader = (LPBITMAPINFOHEADER)malloc(DibSize(sz.cx, sz.cy, 24));
        ASSERT(m_destinationBitmapInfoHeader);
        m_destinationBitmapInfoHeader-&gt;biSize = sizeof(BITMAPINFOHEADER);
        m_destinationBitmapInfoHeader-&gt;biWidth = sz.cx;
        m_destinationBitmapInfoHeader-&gt;biHeight = sz.cy;
        m_destinationBitmapInfoHeader-&gt;biPlanes = 1;
        m_destinationBitmapInfoHeader-&gt;biBitCount = 24;
        m_destinationBitmapInfoHeader-&gt;biCompression = 0;
        m_destinationBitmapInfoHeader-&gt;biSizeImage = DibImageSize(sz.cx, sz.cy, 24);
        m_destinationBitmapInfoHeader-&gt;biXPelsPerMeter = 0;
        m_destinationBitmapInfoHeader-&gt;biYPelsPerMeter = 0;
        m_destinationBitmapInfoHeader-&gt;biClrImportant = 0;
        m_destinationBitmapInfoHeader-&gt;biClrUsed = 0;
    }
}
 
void CTripodDlg::displayMyResults(LPBITMAPINFOHEADER lpThisBitmapInfoHeader)
{
    // displayMyResults: Displays results of doMyImageProcessing() in the videoport
    // Notes: StretchDIBits stretches a device-independent bitmap to the appropriate size
 
    CDC             *pDC;   // Device context to display bitmap data
     
    pDC = GetDC(); 
    int nOldMode = SetStretchBltMode(pDC-&gt;GetSafeHdc(),COLORONCOLOR);
 
    StretchDIBits(
        pDC-&gt;GetSafeHdc(),
        m_rectForProcessedView.left,                // videoportal left-most coordinate
        m_rectForProcessedView.top,                 // videoportal top-most coordinate
        m_rectForProcessedView.Width(),             // videoportal width
        m_rectForProcessedView.Height(),            // videoportal height
        0,                                          // Row position to display bitmap in videoportal
        0,                                          // Col position to display bitmap in videoportal
        lpThisBitmapInfoHeader-&gt;biWidth,         // m_destinationBmp's number of columns
        lpThisBitmapInfoHeader-&gt;biHeight,            // m_destinationBmp's number of rows
        m_destinationBmp,                           // The bitmap to display; use the one resulting from doMyImageProcessing
        (BITMAPINFO*)m_destinationBitmapInfoHeader, // The bitmap's header info e.g. width, height, number of bits etc
        DIB_RGB_COLORS,                             // Use default 24-bit color table
        SRCCOPY                                     // Just display
    );
  
    SetStretchBltMode(pDC-&gt;GetSafeHdc(),nOldMode);
 
    ReleaseDC(pDC);
 
    // Note: 04/24/02 - Added the following:
    // Christopher Wagner cwagner@fas.harvard.edu noticed that memory wasn't being freed
 
    // Recall OnPortalNotificationProcessedview, which gets called everytime
    // a frame of data arrives, performs 3 steps:
    // (1) grayScaleTheFrameData - which mallocs m_destinationBmp
    // (2) doMyImageProcesing
    // (3) displayMyResults - which we're in now
    // Since we're finished with the memory we malloc'ed for m_destinationBmp
    // we should free it:
     
    free(m_destinationBmp);
 
    // End of adds
}
 
void CTripodDlg::grayScaleTheFrameData(LPBITMAPINFOHEADER lpThisBitmapInfoHeader, LPBYTE lpThisBitmapPixelData)
{
 
    // grayScaleTheFrameData: Called by CTripodDlg::OnPortalNotificationBinaryview
    // Task: Read current frame pixel data and computes a grayscale version
 
    unsigned int    W, H;             // Width and Height of current frame [pixels]
    BYTE            *sourceBmp;       // Pointer to current frame of data
    unsigned int    row, col;
    unsigned long   i;
    BYTE            grayValue;
 
    BYTE            redValue;
    BYTE            greenValue;
    BYTE            blueValue;
 
    W = lpThisBitmapInfoHeader-&gt;biWidth;  // biWidth: number of columns
    H = lpThisBitmapInfoHeader-&gt;biHeight; // biHeight: number of rows
 
    // Store pixel data in row-column vector format
    // Recall that each pixel requires 3 bytes (red, blue and green bytes)
    // m_destinationBmp is a protected member and declared in binarizeDlg.h
 
    m_destinationBmp = (BYTE*)malloc(H*3*W*sizeof(BYTE));
 
    // Point to the current frame's pixel data
    sourceBmp = lpThisBitmapPixelData;
 
    for (row = 0; row &lt; H; row++) {
        for (col = 0; col &lt; W; col++) {
 
            // Recall each pixel is composed of 3 bytes
            i = (unsigned long)(row*3*W + 3*col);
         
            // The source pixel has a blue, green andred value:
            blueValue  = *(sourceBmp + i);
            greenValue = *(sourceBmp + i + 1);
            redValue   = *(sourceBmp + i + 2);
 
            // A standard equation for computing a grayscale value based on RGB values
            grayValue = (BYTE)(0.299*redValue + 0.587*greenValue + 0.114*blueValue);
 
            // The destination BMP will be a grayscale version of the source BMP
            *(m_destinationBmp + i)     = grayValue;
            *(m_destinationBmp + i + 1) = grayValue;
            *(m_destinationBmp + i + 2) = grayValue;
             
        }
    }
}
 
 
void CTripodDlg::doMyImageProcessing(LPBITMAPINFOHEADER lpThisBitmapInfoHeader)
{
    // doMyImageProcessing:  This is where you'd write your own image processing code
    // Task: Read a pixel's grayscale value and process accordingly
 
    unsigned int    W, H;           // Width and Height of current frame [pixels]
    unsigned int    row, col;       // Pixel's row and col positions
    unsigned long   i;              // Dummy variable for row-column vector
    int     upperThreshold = 60;    // Gradient strength nessicary to start edge
    int     lowerThreshold = 30;    // Minimum gradient strength to continue edge
    unsigned long iOffset;          // Variable to offset row-column vector during sobel mask
    int rowOffset;                  // Row offset from the current pixel
    int colOffset;                  // Col offset from the current pixel
    int rowTotal = 0;               // Row position of offset pixel
    int colTotal = 0;               // Col position of offset pixel
    int Gx;                         // Sum of Sobel mask products values in the x direction
    int Gy;                         // Sum of Sobel mask products values in the y direction
    float thisAngle;                // Gradient direction based on Gx and Gy
    int newAngle;                   // Approximation of the gradient direction
    bool edgeEnd;                   // Stores whether or not the edge is at the edge of the possible image
    int GxMask[3][3];               // Sobel mask in the x direction
    int GyMask[3][3];               // Sobel mask in the y direction
    int newPixel;                   // Sum pixel values for gaussian
    int gaussianMask[5][5];         // Gaussian mask
 
    W = lpThisBitmapInfoHeader-&gt;biWidth;  // biWidth: number of columns
    H = lpThisBitmapInfoHeader-&gt;biHeight; // biHeight: number of rows
     
    for (row = 0; row &lt; H; row++) {
        for (col = 0; col &lt; W; col++) {
            edgeDir[row][col] = 0;
        }
    }
 
    /* Declare Sobel masks */
    GxMask[0][0] = -1; GxMask[0][1] = 0; GxMask[0][2] = 1;
    GxMask[1][0] = -2; GxMask[1][1] = 0; GxMask[1][2] = 2;
    GxMask[2][0] = -1; GxMask[2][1] = 0; GxMask[2][2] = 1;
     
    GyMask[0][0] =  1; GyMask[0][1] =  2; GyMask[0][2] =  1;
    GyMask[1][0] =  0; GyMask[1][1] =  0; GyMask[1][2] =  0;
    GyMask[2][0] = -1; GyMask[2][1] = -2; GyMask[2][2] = -1;
 
    /* Declare Gaussian mask */
    gaussianMask[0][0] = 2;     gaussianMask[0][1] = 4;     gaussianMask[0][2] = 5;     gaussianMask[0][3] = 4;     gaussianMask[0][4] = 2;
    gaussianMask[1][0] = 4;     gaussianMask[1][1] = 9;     gaussianMask[1][2] = 12;    gaussianMask[1][3] = 9;     gaussianMask[1][4] = 4;
    gaussianMask[2][0] = 5;     gaussianMask[2][1] = 12;    gaussianMask[2][2] = 15;    gaussianMask[2][3] = 12;    gaussianMask[2][4] = 2;
    gaussianMask[3][0] = 4;     gaussianMask[3][1] = 9;     gaussianMask[3][2] = 12;    gaussianMask[3][3] = 9;     gaussianMask[3][4] = 4;
    gaussianMask[4][0] = 2;     gaussianMask[4][1] = 4;     gaussianMask[4][2] = 5;     gaussianMask[4][3] = 4;     gaussianMask[4][4] = 2;
     
 
    /* Gaussian Blur */
    for (row = 2; row &lt; H-2; row++) {
        for (col = 2; col &lt; W-2; col++) {
            newPixel = 0;
            for (rowOffset=-2; rowOffset&lt;=2; rowOffset++) {
                for (colOffset=-2; colOffset&lt;=2; colOffset++) {
                    rowTotal = row + rowOffset;
                    colTotal = col + colOffset;
                    iOffset = (unsigned long)(rowTotal*3*W + colTotal*3);
                    newPixel += (*(m_destinationBmp + iOffset)) * gaussianMask[2 + rowOffset][2 + colOffset];
                }
            }
            i = (unsigned long)(row*3*W + col*3);
            *(m_destinationBmp + i) = newPixel / 159;
        }
    }
 
    /* Determine edge directions and gradient strengths */
    for (row = 1; row &lt; H-1; row++) {
        for (col = 1; col &lt; W-1; col++) {
            i = (unsigned long)(row*3*W + 3*col);
            Gx = 0;
            Gy = 0;
            /* Calculate the sum of the Sobel mask times the nine surrounding pixels in the x and y direction */
            for (rowOffset=-1; rowOffset&lt;=1; rowOffset++) {
                for (colOffset=-1; colOffset&lt;=1; colOffset++) {
                    rowTotal = row + rowOffset;
                    colTotal = col + colOffset;
                    iOffset = (unsigned long)(rowTotal*3*W + colTotal*3);
                    Gx = Gx + (*(m_destinationBmp + iOffset) * GxMask[rowOffset + 1][colOffset + 1]);
                    Gy = Gy + (*(m_destinationBmp + iOffset) * GyMask[rowOffset + 1][colOffset + 1]);
                }
            }
 
            gradient[row][col] = sqrt(pow(Gx,2.0) + pow(Gy,2.0));   // Calculate gradient strength         
            thisAngle = (atan2(Gx,Gy)/3.14159) * 180.0;     // Calculate actual direction of edge
             
            /* Convert actual edge direction to approximate value */
            if ( ( (thisAngle &lt; 22.5) &amp;&amp; (thisAngle &gt; -22.5) ) || (thisAngle &gt; 157.5) || (thisAngle &lt; -157.5) )
                newAngle = 0;
            if ( ( (thisAngle &gt; 22.5) &amp;&amp; (thisAngle &lt; 67.5) ) || ( (thisAngle &lt; -112.5) &amp;&amp; (thisAngle &gt; -157.5) ) )
                newAngle = 45;
            if ( ( (thisAngle &gt; 67.5) &amp;&amp; (thisAngle &lt; 112.5) ) || ( (thisAngle &lt; -67.5) &amp;&amp; (thisAngle &gt; -112.5) ) )
                newAngle = 90;
            if ( ( (thisAngle &gt; 112.5) &amp;&amp; (thisAngle &lt; 157.5) ) || ( (thisAngle &lt; -22.5) &amp;&amp; (thisAngle &gt; -67.5) ) )
                newAngle = 135;
                 
            edgeDir[row][col] = newAngle;       // Store the approximate edge direction of each pixel in one array
        }
    }
 
    /* Trace along all the edges in the image */
    for (row = 1; row &lt; H - 1; row++) {
        for (col = 1; col &lt; W - 1; col++) {
            edgeEnd = false;
            if (gradient[row][col] &gt; upperThreshold) {       // Check to see if current pixel has a high enough gradient strength to be part of an edge
                /* Switch based on current pixel's edge direction */
                switch (edgeDir[row][col]){    
                    case 0:
                        findEdge(0, 1, row, col, 0, lowerThreshold);
                        break;
                    case 45:
                        findEdge(1, 1, row, col, 45, lowerThreshold);
                        break;
                    case 90:
                        findEdge(1, 0, row, col, 90, lowerThreshold);
                        break;
                    case 135:
                        findEdge(1, -1, row, col, 135, lowerThreshold);
                        break;
                    default :
                        i = (unsigned long)(row*3*W + 3*col);
                        *(m_destinationBmp + i) =
                        *(m_destinationBmp + i + 1) =
                        *(m_destinationBmp + i + 2) = 0;
                        break;
                    }
                }
            else {
                i = (unsigned long)(row*3*W + 3*col);
                    *(m_destinationBmp + i) =
                    *(m_destinationBmp + i + 1) =
                    *(m_destinationBmp + i + 2) = 0;
            }  
        }
    }
     
    /* Suppress any pixels not changed by the edge tracing */
    for (row = 0; row &lt; H; row++) {
        for (col = 0; col &lt; W; col++) { 
            // Recall each pixel is composed of 3 bytes
            i = (unsigned long)(row*3*W + 3*col);
            // If a pixel's grayValue is not black or white make it black
            if( ((*(m_destinationBmp + i) != 255) &amp;&amp; (*(m_destinationBmp + i) != 0)) || ((*(m_destinationBmp + i + 1) != 255) &amp;&amp; (*(m_destinationBmp + i + 1) != 0)) || ((*(m_destinationBmp + i + 2) != 255) &amp;&amp; (*(m_destinationBmp + i + 2) != 0)) )
                *(m_destinationBmp + i) =
                *(m_destinationBmp + i + 1) =
                *(m_destinationBmp + i + 2) = 0; // Make pixel black
        }
    }
 
    /* Non-maximum Suppression */
    for (row = 1; row &lt; H - 1; row++) {
        for (col = 1; col &lt; W - 1; col++) {
            i = (unsigned long)(row*3*W + 3*col);
            if (*(m_destinationBmp + i) == 255) {       // Check to see if current pixel is an edge
                /* Switch based on current pixel's edge direction */
                switch (edgeDir[row][col]) {       
                    case 0:
                        suppressNonMax( 1, 0, row, col, 0, lowerThreshold);
                        break;
                    case 45:
                        suppressNonMax( 1, -1, row, col, 45, lowerThreshold);
                        break;
                    case 90:
                        suppressNonMax( 0, 1, row, col, 90, lowerThreshold);
                        break;
                    case 135:
                        suppressNonMax( 1, 1, row, col, 135, lowerThreshold);
                        break;
                    default :
                        break;
                }
            }  
        }
    }
     
}
 
void CTripodDlg::findEdge(int rowShift, int colShift, int row, int col, int dir, int lowerThreshold)
{
    int W = 320;
    int H = 240;
    int newRow;
    int newCol;
    unsigned long i;
    bool edgeEnd = false;
 
    /* Find the row and column values for the next possible pixel on the edge */
    if (colShift &lt; 0) {
        if (col &gt; 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col &lt; W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;     // If the next pixel would be off image, don't do the while loop
    if (rowShift &lt; 0) {
        if (row &gt; 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row &lt; H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
         
    /* Determine edge directions and gradient strengths */
    while ( (edgeDir[newRow][newCol]==dir) &amp;&amp; !edgeEnd &amp;&amp; (gradient[newRow][newCol] &gt; lowerThreshold) ) {
        /* Set the new pixel as white to show it is an edge */
        i = (unsigned long)(newRow*3*W + 3*newCol);
        *(m_destinationBmp + i) =
        *(m_destinationBmp + i + 1) =
        *(m_destinationBmp + i + 2) = 255;
        if (colShift &lt; 0) {
            if (newCol &gt; 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol &lt; W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift &lt; 0) {
            if (newRow &gt; 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow &lt; H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
    }  
}
 
void CTripodDlg::suppressNonMax(int rowShift, int colShift, int row, int col, int dir, int lowerThreshold)
{
    int W = 320;
    int H = 240;
    int newRow = 0;
    int newCol = 0;
    unsigned long i;
    bool edgeEnd = false;
    float nonMax[320][3];           // Temporarily stores gradients and positions of pixels in parallel edges
    int pixelCount = 0;                 // Stores the number of pixels in parallel edges
    int count;                      // A for loop counter
    int max[3];                     // Maximum point in a wide edge
     
    if (colShift &lt; 0) {
        if (col &gt; 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col &lt; W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;     // If the next pixel would be off image, don't do the while loop
    if (rowShift &lt; 0) {
        if (row &gt; 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row &lt; H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
    i = (unsigned long)(newRow*3*W + 3*newCol);
    /* Find non-maximum parallel edges tracing up */
    while ((edgeDir[newRow][newCol] == dir) &amp;&amp; !edgeEnd &amp;&amp; (*(m_destinationBmp + i) == 255)) {
        if (colShift &lt; 0) {
            if (newCol &gt; 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol &lt; W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift &lt; 0) {
            if (newRow &gt; 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow &lt; H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
        nonMax[pixelCount][0] = newRow;
        nonMax[pixelCount][1] = newCol;
        nonMax[pixelCount][2] = gradient[newRow][newCol];
        pixelCount++;
        i = (unsigned long)(newRow*3*W + 3*newCol);
    }
 
    /* Find non-maximum parallel edges tracing down */
    edgeEnd = false;
    colShift *= -1;
    rowShift *= -1;
    if (colShift &lt; 0) {
        if (col &gt; 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col &lt; W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;
    if (rowShift &lt; 0) {
        if (row &gt; 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row &lt; H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
    i = (unsigned long)(newRow*3*W + 3*newCol);
    while ((edgeDir[newRow][newCol] == dir) &amp;&amp; !edgeEnd &amp;&amp; (*(m_destinationBmp + i) == 255)) {
        if (colShift &lt; 0) {
            if (newCol &gt; 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol &lt; W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift &lt; 0) {
            if (newRow &gt; 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow &lt; H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
        nonMax[pixelCount][0] = newRow;
        nonMax[pixelCount][1] = newCol;
        nonMax[pixelCount][2] = gradient[newRow][newCol];
        pixelCount++;
        i = (unsigned long)(newRow*3*W + 3*newCol);
    }
 
    /* Suppress non-maximum edges */
    max[0] = 0;
    max[1] = 0;
    max[2] = 0;
    for (count = 0; count &lt; pixelCount; count++) {
        if (nonMax[count][2] &gt; max[2]) {
            max[0] = nonMax[count][0];
            max[1] = nonMax[count][1];
            max[2] = nonMax[count][2];
        }
    }
    for (count = 0; count &lt; pixelCount; count++) {
        i = (unsigned long)(nonMax[count][0]*3*W + 3*nonMax[count][1]);
        *(m_destinationBmp + i) =
        *(m_destinationBmp + i + 1) =
        *(m_destinationBmp + i + 2) = 0;
    }
}

الگوریتم Canny در سی پلاس پلاس قسمت 1
الگوریتم Canny در سی پلاس پلاس قسمت 2
الگوریتم Canny در سی پلاس پلاس قسمت 3
الگوریتم Canny در سی پلاس پلاس قسمت 4

الگوریتم Canny در ++C

لبه یاب کنی توسط جان اف کنی در سال 1986 ایجاد شد و هنوز یک لبه یاب استاندارد و با دقت و کیفیت بالا میباشد.الگوریتم لبه یابی کنی یکی از بهترین لبه یابها تا به امروز است. در ادامه روش کار این الگوریتم و هم چنین کد الگوریتم Canny در ++C را بررسی خواهیم کرد. این الگوریتم لبه یابی از سه بخش اصلی زیر تشکیل شده است:

  • تضعیف نویز
  • پیدا کردن نقاطی که بتوان آنها را به عنوان لبه در نظر گرفت
  • حذب نقاطی که احتمال لبه بودن آنها کم است

 

معیارهایی که در لبه یاب کنی مطرح است:
1 -پایین آوردن نرخ خطا- یعنی تا حد امکان هیچ لبه ای در تصویر نباید گم شود و هم چنین هیچ چیزی که لبه نیست نباید به جای لبه فرض شود. لبه هان پیدا شده تا حد ممکن به لبه ها اصلی
نزدیک باشند.

2 -لبه در مکان واقعی خود باشد- یعنی تا حد ممکن لبه ها کمترین فاصله را با مکان واقعی خود داشته باشند.
3 -بران هر لبه فقط یک پاسخ داشته باشیم.

4 -لبه ها کمترین ضخامت را داشته باشند- (در صورت امکان یک پیکسل).
لبه یاب کنی بخاطر توانایی در تولید لبه های نازک تا حد یک ییکسل برای لبه های پیوسته معروف شده است. این لبه یاب شامل چهار مرحله و چهار ورودی زیر است:
یک تصویر ورودی
یک پارامتر به نام سیگما جهت مقدار نرم کنندگی تصویر
یک حد آستانه بالا (Th)
یک حد آستانه پایین (Tl)

 

مراحل الگوریتم Canny:

1- در ابتدا باید تصویر رنگی را به جهت لبه یابی بهتر به یک تصویر سطح خاکسترن تبدیب کرد.

2- نویز را از تصویر دریافتی حذف کرد. بدلیل اینکه فیلتر گاوسین از یک ماسک ساده برای حذف نویز استفاده می کند لبه یاب کنی در مرحله اول برای حذف نویز آن را بکار میگیرد.

3- در یک تصویر سطح خاکستر جایی را که بیشترین تغییرات را داشته باشند به عنوان لبه در نظر گرفته می شوند و این مکانها با گرفتن گرادیان تصویر با استفاده عملگر سوبل بدست می آیند. سپس لبه های مات یافت شده به لبه های تیزتر تبدیل می شوند.

4- برخی از لبه های کشف شده واقعا لبه نیستند و در واقع نویز هستند که باید آنها توسط حد آستانه هیسترزیس فیلتر شوند.هیسترزیس از دو حد آستانه بالاتر (Th) و حد آستانه پایین تر (Tl) استفاده کرده و کنی پیشنهاد می کند که نسبت استانه بالا به پایین سه به یک باشد.

 این روش بیشتر به کشف لبه های ضعیف به درستی می پردازد و کمتر فریب نویز را می خورد و از بقیه روش ها بهتر است.

 

الگوریتم Canny    عملکرد الگوریتم Canny

 

 

 

کد الگوریتم Canny در ++C:

برای الگوریتم Canny دو کد زیر ارائه می شود که کد شماره 2 کد کاملتری است.

کد شماره  الگوریتم 1 الگوریتم Canny در ++C:

در زیر استفاده از الگوریتم کنی در ++C است. توجه داشته باشید که تصویر ابتدا به تصویر سیاه و سفید تبدیل می شود، سپس فیلتر گاوسی برای کاهش نویز در تصویر استفاده می شود. سپس الگوریتم Canny برای تشخیص لبه استفاده می شود.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// CannyTutorial.cpp : Defines the entry point for the console application. 
// Environment: Visual studio 2015, Windows 10
// Assumptions: Opecv is installed configured in the visual studio project
// Opencv version: OpenCV 3.1
 
#include "stdafx.h"
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<string>
#include<iostream>
 
 
int main()
{
 
    cv::Mat imgOriginal;        // input image
    cv::Mat imgGrayscale;        // grayscale of input image
    cv::Mat imgBlurred;            // intermediate blured image
    cv::Mat imgCanny;            // Canny edge image
 
    std::cout << "Please enter an image filename : ";     std::string img_addr;     std::cin >> img_addr;
 
    std::cout << "Searching for " + img_addr << std::endl;
 
    imgOriginal = cv::imread(img_addr);            // open image
 
    if (imgOriginal.empty()) {                                    // if unable to open image
        std::cout << "error: image not read from file\n\n";        // show error message on command line
        return(0);                                                // and exit program
    }
 
    cv::cvtColor(imgOriginal, imgGrayscale, CV_BGR2GRAY);        // convert to grayscale
 
    cv::GaussianBlur(imgGrayscale,            // input image
        imgBlurred,                            // output image
        cv::Size(5, 5),                        // smoothing window width and height in pixels
        1.5);                                // sigma value, determines how much the image will be blurred
 
    cv::Canny(imgBlurred,            // input image
        imgCanny,                    // output image
        100,                        // low threshold
        200);                        // high threshold
 
 
    // Declare windows
    // Note: you can use CV_WINDOW_NORMAL which allows resizing the window
    // or CV_WINDOW_AUTOSIZE for a fixed size window matching the resolution of the image
    // CV_WINDOW_AUTOSIZE is the default
    cv::namedWindow("imgOriginal", CV_WINDOW_AUTOSIZE);        
    cv::namedWindow("imgCanny", CV_WINDOW_AUTOSIZE);
 
    //Show windows
    cv::imshow("imgOriginal", imgOriginal);        
    cv::imshow("imgCanny", imgCanny);
 
    cv::waitKey(0);                    // hold windows open until user presses a key
    return 0;
}

 

دانلود کد فوق از طریق لینک زیر:

رمز فایل : behsanandish.com

 

 

کد شماره 2:

مرحله 1: یک blur(تار کننده) گاوسی را اعمال کنید.

اول متغیرهای ضروری اعلام شده اند و بعضی از آنها اولیه هستند. سپس Blur گاوسی اعمال می شود. برای انجام این کار یک ماسک 5×5 بر روی تصویر منتقل می شود. هر پیکسل به صورت مجموع مقادیر پیکسل در محدوده 5×5 آن ضربدر وزن گاوسی متناظر تقسیم شده توسط وزن مجموع کل ماسک تعریف می شود.

 

ماسک گاوسی

ماسک گاوسی

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
#include "stdafx.h"
#include "tripod.h"
#include "tripodDlg.h"
 
#include "LVServerDefs.h"
#include "math.h"
#include <fstream>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
 
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
using namespace std;
 
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
 
class CAboutDlg : public CDialog
{
public:
    CAboutDlg();
 
// Dialog Data
    //{{AFX_DATA(CAboutDlg)
    enum { IDD = IDD_ABOUTBOX };
    //}}AFX_DATA
 
    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CAboutDlg)
    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
    //}}AFX_VIRTUAL
 
// Implementation
protected:
    //{{AFX_MSG(CAboutDlg)
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()
};
 
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
    //{{AFX_DATA_INIT(CAboutDlg)
    //}}AFX_DATA_INIT
}
 
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CAboutDlg)
    //}}AFX_DATA_MAP
}
 
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
    //{{AFX_MSG_MAP(CAboutDlg)
        // No message handlers
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/////////////////////////////////////////////////////////////////////////////
// CTripodDlg dialog
 
CTripodDlg::CTripodDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CTripodDlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CTripodDlg)
        // NOTE: the ClassWizard will add member initialization here
    //}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
 
    //////////////// Set destination BMP to NULL first
    m_destinationBitmapInfoHeader = NULL;
 
}
 
////////////////////// Additional generic functions
 
static unsigned PixelBytes(int w, int bpp)
{
    return (w * bpp + 7) / 8;
}
 
static unsigned DibRowSize(int w, int bpp)
{
    return (w * bpp + 31) / 32 * 4;
}
 
static unsigned DibRowSize(LPBITMAPINFOHEADER pbi)
{
    return DibRowSize(pbi->biWidth, pbi->biBitCount);
}
 
static unsigned DibRowPadding(int w, int bpp)
{
    return DibRowSize(w, bpp) - PixelBytes(w, bpp);
}
 
static unsigned DibRowPadding(LPBITMAPINFOHEADER pbi)
{
    return DibRowPadding(pbi->biWidth, pbi->biBitCount);
}
 
static unsigned DibImageSize(int w, int h, int bpp)
{
    return h * DibRowSize(w, bpp);
}
 
static size_t DibSize(int w, int h, int bpp)
{
    return sizeof (BITMAPINFOHEADER) + DibImageSize(w, h, bpp);
}
 
/////////////////////// end of generic functions
 
 
void CTripodDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CTripodDlg)
    DDX_Control(pDX, IDC_PROCESSEDVIEW, m_cVideoProcessedView);
    DDX_Control(pDX, IDC_UNPROCESSEDVIEW, m_cVideoUnprocessedView);
    //}}AFX_DATA_MAP
}
 
BEGIN_MESSAGE_MAP(CTripodDlg, CDialog)
    //{{AFX_MSG_MAP(CTripodDlg)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_BN_CLICKED(IDEXIT, OnExit)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/////////////////////////////////////////////////////////////////////////////
// CTripodDlg message handlers
 
BOOL CTripodDlg::OnInitDialog()
{
    CDialog::OnInitDialog();
 
    // Add "About..." menu item to system menu.
 
    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }
 
    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon
     
    // TODO: Add extra initialization here
 
    // For Unprocessed view videoportal (top one)
    char sRegUnprocessedView[] = "HKEY_LOCAL_MACHINE\\Software\\UnprocessedView";
    m_cVideoUnprocessedView.PrepareControl("UnprocessedView", sRegUnprocessedView, 0 );
    m_cVideoUnprocessedView.EnableUIElements(UIELEMENT_STATUSBAR,0,TRUE);
    m_cVideoUnprocessedView.ConnectCamera2();
    m_cVideoUnprocessedView.SetEnablePreview(TRUE);
 
    // For binary view videoportal (bottom one)
    char sRegProcessedView[] = "HKEY_LOCAL_MACHINE\\Software\\ProcessedView";
    m_cVideoProcessedView.PrepareControl("ProcessedView", sRegProcessedView, 0 );  
    m_cVideoProcessedView.EnableUIElements(UIELEMENT_STATUSBAR,0,TRUE);
    m_cVideoProcessedView.ConnectCamera2();
    m_cVideoProcessedView.SetEnablePreview(TRUE);
 
    // Initialize the size of binary videoportal
    m_cVideoProcessedView.SetPreviewMaxHeight(240);
    m_cVideoProcessedView.SetPreviewMaxWidth(320);
 
    // Uncomment if you wish to fix the live videoportal's size
    // m_cVideoUnprocessedView.SetPreviewMaxHeight(240);
    // m_cVideoUnprocessedView.SetPreviewMaxWidth(320);
 
    // Find the screen coodinates of the binary videoportal
    m_cVideoProcessedView.GetWindowRect(m_rectForProcessedView);
    ScreenToClient(m_rectForProcessedView);
    allocateDib(CSize(320, 240));
 
    // Start grabbing frame data for Procssed videoportal (bottom one)
    m_cVideoProcessedView.StartVideoHook(0);
 
    return TRUE;  // return TRUE  unless you set the focus to a control
}
 
void CTripodDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID & 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        dlgAbout.DoModal();
    }
    else
    {
        CDialog::OnSysCommand(nID, lParam);
    }
}
 
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.
 
void CTripodDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting
 
        SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
 
        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
 
        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}
 
// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTripodDlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}
 
void CTripodDlg::OnExit()
{
    // TODO: Add your control notification handler code here
 
    // Kill live view videoportal (top one)
    m_cVideoUnprocessedView.StopVideoHook(0);
    m_cVideoUnprocessedView.DisconnectCamera();
     
    // Kill binary view videoportal (bottom one)
    m_cVideoProcessedView.StopVideoHook(0);
    m_cVideoProcessedView.DisconnectCamera();  
 
    // Kill program
    DestroyWindow();   
 
     
 
}
 
BEGIN_EVENTSINK_MAP(CTripodDlg, CDialog)
    //{{AFX_EVENTSINK_MAP(CTripodDlg)
    ON_EVENT(CTripodDlg, IDC_PROCESSEDVIEW, 1 /* PortalNotification */, OnPortalNotificationProcessedview, VTS_I4 VTS_I4 VTS_I4 VTS_I4)
    //}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()
 
void CTripodDlg::OnPortalNotificationProcessedview(long lMsg, long lParam1, long lParam2, long lParam3)
{
    // TODO: Add your control notification handler code here
     
    // This function is called at the camera's frame rate
     
#define NOTIFICATIONMSG_VIDEOHOOK   10
 
    // Declare some useful variables
    // QCSDKMFC.pdf (Quickcam MFC documentation) p. 103 explains the variables lParam1, lParam2, lParam3 too
     
    LPBITMAPINFOHEADER lpBitmapInfoHeader; // Frame's info header contains info like width and height
    LPBYTE lpBitmapPixelData; // This pointer-to-long will point to the start of the frame's pixel data
    unsigned long lTimeStamp; // Time when frame was grabbed
 
    switch(lMsg) {
        case NOTIFICATIONMSG_VIDEOHOOK:
            {
                lpBitmapInfoHeader = (LPBITMAPINFOHEADER) lParam1;
                lpBitmapPixelData = (LPBYTE) lParam2;
                lTimeStamp = (unsigned long) lParam3;
 
                grayScaleTheFrameData(lpBitmapInfoHeader, lpBitmapPixelData);
                doMyImageProcessing(lpBitmapInfoHeader); // Place where you'd add your image processing code
                displayMyResults(lpBitmapInfoHeader);
 
            }
            break;
 
        default:
            break;
    }  
}
 
void CTripodDlg::allocateDib(CSize sz)
{
    // Purpose: allocate information for a device independent bitmap (DIB)
    // Called from OnInitVideo
 
    if(m_destinationBitmapInfoHeader) {
        free(m_destinationBitmapInfoHeader);
        m_destinationBitmapInfoHeader = NULL;
    }
 
    if(sz.cx | sz.cy) {
        m_destinationBitmapInfoHeader = (LPBITMAPINFOHEADER)malloc(DibSize(sz.cx, sz.cy, 24));
        ASSERT(m_destinationBitmapInfoHeader);
        m_destinationBitmapInfoHeader->biSize = sizeof(BITMAPINFOHEADER);
        m_destinationBitmapInfoHeader->biWidth = sz.cx;
        m_destinationBitmapInfoHeader->biHeight = sz.cy;
        m_destinationBitmapInfoHeader->biPlanes = 1;
        m_destinationBitmapInfoHeader->biBitCount = 24;
        m_destinationBitmapInfoHeader->biCompression = 0;
        m_destinationBitmapInfoHeader->biSizeImage = DibImageSize(sz.cx, sz.cy, 24);
        m_destinationBitmapInfoHeader->biXPelsPerMeter = 0;
        m_destinationBitmapInfoHeader->biYPelsPerMeter = 0;
        m_destinationBitmapInfoHeader->biClrImportant = 0;
        m_destinationBitmapInfoHeader->biClrUsed = 0;
    }
}
 
void CTripodDlg::displayMyResults(LPBITMAPINFOHEADER lpThisBitmapInfoHeader)
{
    // displayMyResults: Displays results of doMyImageProcessing() in the videoport
    // Notes: StretchDIBits stretches a device-independent bitmap to the appropriate size
 
    CDC             *pDC;   // Device context to display bitmap data
     
    pDC = GetDC(); 
    int nOldMode = SetStretchBltMode(pDC->GetSafeHdc(),COLORONCOLOR);
 
    StretchDIBits(
        pDC->GetSafeHdc(),
        m_rectForProcessedView.left,                // videoportal left-most coordinate
        m_rectForProcessedView.top,                 // videoportal top-most coordinate
        m_rectForProcessedView.Width(),             // videoportal width
        m_rectForProcessedView.Height(),            // videoportal height
        0,                                          // Row position to display bitmap in videoportal
        0,                                          // Col position to display bitmap in videoportal
        lpThisBitmapInfoHeader->biWidth,         // m_destinationBmp's number of columns
        lpThisBitmapInfoHeader->biHeight,            // m_destinationBmp's number of rows
        m_destinationBmp,                           // The bitmap to display; use the one resulting from doMyImageProcessing
        (BITMAPINFO*)m_destinationBitmapInfoHeader, // The bitmap's header info e.g. width, height, number of bits etc
        DIB_RGB_COLORS,                             // Use default 24-bit color table
        SRCCOPY                                     // Just display
    );
  
    SetStretchBltMode(pDC->GetSafeHdc(),nOldMode);
 
    ReleaseDC(pDC);
 
    // Note: 04/24/02 - Added the following:
    // Christopher Wagner cwagner@fas.harvard.edu noticed that memory wasn't being freed
 
    // Recall OnPortalNotificationProcessedview, which gets called everytime
    // a frame of data arrives, performs 3 steps:
    // (1) grayScaleTheFrameData - which mallocs m_destinationBmp
    // (2) doMyImageProcesing
    // (3) displayMyResults - which we're in now
    // Since we're finished with the memory we malloc'ed for m_destinationBmp
    // we should free it:
     
    free(m_destinationBmp);
 
    // End of adds
}
 
void CTripodDlg::grayScaleTheFrameData(LPBITMAPINFOHEADER lpThisBitmapInfoHeader, LPBYTE lpThisBitmapPixelData)
{
 
    // grayScaleTheFrameData: Called by CTripodDlg::OnPortalNotificationBinaryview
    // Task: Read current frame pixel data and computes a grayscale version
 
    unsigned int    W, H;             // Width and Height of current frame [pixels]
    BYTE            *sourceBmp;       // Pointer to current frame of data
    unsigned int    row, col;
    unsigned long   i;
    BYTE            grayValue;
 
    BYTE            redValue;
    BYTE            greenValue;
    BYTE            blueValue;
 
    W = lpThisBitmapInfoHeader->biWidth;  // biWidth: number of columns
    H = lpThisBitmapInfoHeader->biHeight; // biHeight: number of rows
 
    // Store pixel data in row-column vector format
    // Recall that each pixel requires 3 bytes (red, blue and green bytes)
    // m_destinationBmp is a protected member and declared in binarizeDlg.h
 
    m_destinationBmp = (BYTE*)malloc(H*3*W*sizeof(BYTE));
 
    // Point to the current frame's pixel data
    sourceBmp = lpThisBitmapPixelData;
 
    for (row = 0; row < H; row++) {
        for (col = 0; col < W; col++) { // Recall each pixel is composed of 3 bytes i = (unsigned long)(row*3*W + 3*col); // The source pixel has a blue, green andred value: blueValue = *(sourceBmp + i); greenValue = *(sourceBmp + i + 1); redValue = *(sourceBmp + i + 2); // A standard equation for computing a grayscale value based on RGB values grayValue = (BYTE)(0.299*redValue + 0.587*greenValue + 0.114*blueValue); // The destination BMP will be a grayscale version of the source BMP *(m_destinationBmp + i) = grayValue; *(m_destinationBmp + i + 1) = grayValue; *(m_destinationBmp + i + 2) = grayValue; } } } void CTripodDlg::doMyImageProcessing(LPBITMAPINFOHEADER lpThisBitmapInfoHeader) { // doMyImageProcessing: This is where you'd write your own image processing code // Task: Read a pixel's grayscale value and process accordingly unsigned int W, H; // Width and Height of current frame [pixels] unsigned int row, col; // Pixel's row and col positions unsigned long i; // Dummy variable for row-column vector int upperThreshold = 60; // Gradient strength nessicary to start edge int lowerThreshold = 30; // Minimum gradient strength to continue edge unsigned long iOffset; // Variable to offset row-column vector during sobel mask int rowOffset; // Row offset from the current pixel int colOffset; // Col offset from the current pixel int rowTotal = 0; // Row position of offset pixel int colTotal = 0; // Col position of offset pixel int Gx; // Sum of Sobel mask products values in the x direction int Gy; // Sum of Sobel mask products values in the y direction float thisAngle; // Gradient direction based on Gx and Gy int newAngle; // Approximation of the gradient direction bool edgeEnd; // Stores whether or not the edge is at the edge of the possible image int GxMask[3][3]; // Sobel mask in the x direction int GyMask[3][3]; // Sobel mask in the y direction int newPixel; // Sum pixel values for gaussian int gaussianMask[5][5]; // Gaussian mask W = lpThisBitmapInfoHeader->biWidth;  // biWidth: number of columns
    H = lpThisBitmapInfoHeader->biHeight; // biHeight: number of rows
     
    for (row = 0; row < H; row++) {
        for (col = 0; col < W; col++) {
            edgeDir[row][col] = 0;
        }
    }
 
    /* Declare Sobel masks */
    GxMask[0][0] = -1; GxMask[0][1] = 0; GxMask[0][2] = 1;
    GxMask[1][0] = -2; GxMask[1][1] = 0; GxMask[1][2] = 2;
    GxMask[2][0] = -1; GxMask[2][1] = 0; GxMask[2][2] = 1;
     
    GyMask[0][0] =  1; GyMask[0][1] =  2; GyMask[0][2] =  1;
    GyMask[1][0] =  0; GyMask[1][1] =  0; GyMask[1][2] =  0;
    GyMask[2][0] = -1; GyMask[2][1] = -2; GyMask[2][2] = -1;
 
    /* Declare Gaussian mask */
    gaussianMask[0][0] = 2;     gaussianMask[0][1] = 4;     gaussianMask[0][2] = 5;     gaussianMask[0][3] = 4;     gaussianMask[0][4] = 2;
    gaussianMask[1][0] = 4;     gaussianMask[1][1] = 9;     gaussianMask[1][2] = 12;    gaussianMask[1][3] = 9;     gaussianMask[1][4] = 4;
    gaussianMask[2][0] = 5;     gaussianMask[2][1] = 12;    gaussianMask[2][2] = 15;    gaussianMask[2][3] = 12;    gaussianMask[2][4] = 2;
    gaussianMask[3][0] = 4;     gaussianMask[3][1] = 9;     gaussianMask[3][2] = 12;    gaussianMask[3][3] = 9;     gaussianMask[3][4] = 4;
    gaussianMask[4][0] = 2;     gaussianMask[4][1] = 4;     gaussianMask[4][2] = 5;     gaussianMask[4][3] = 4;     gaussianMask[4][4] = 2;
     
 
    /* Gaussian Blur */
    for (row = 2; row < H-2; row++) {
        for (col = 2; col < W-2; col++) {
            newPixel = 0;
            for (rowOffset=-2; rowOffset<=2; rowOffset++) {
                for (colOffset=-2; colOffset<=2; colOffset++) {
                    rowTotal = row + rowOffset;
                    colTotal = col + colOffset;
                    iOffset = (unsigned long)(rowTotal*3*W + colTotal*3);
                    newPixel += (*(m_destinationBmp + iOffset)) * gaussianMask[2 + rowOffset][2 + colOffset];
                }
            }
            i = (unsigned long)(row*3*W + col*3);
            *(m_destinationBmp + i) = newPixel / 159;
        }
    }
 
    /* Determine edge directions and gradient strengths */
    for (row = 1; row < H-1; row++) {
        for (col = 1; col < W-1; col++) {
            i = (unsigned long)(row*3*W + 3*col);
            Gx = 0;
            Gy = 0;
            /* Calculate the sum of the Sobel mask times the nine surrounding pixels in the x and y direction */
            for (rowOffset=-1; rowOffset<=1; rowOffset++) {
                for (colOffset=-1; colOffset<=1; colOffset++) {
                    rowTotal = row + rowOffset;
                    colTotal = col + colOffset;
                    iOffset = (unsigned long)(rowTotal*3*W + colTotal*3);
                    Gx = Gx + (*(m_destinationBmp + iOffset) * GxMask[rowOffset + 1][colOffset + 1]);
                    Gy = Gy + (*(m_destinationBmp + iOffset) * GyMask[rowOffset + 1][colOffset + 1]);
                }
            }
 
            gradient[row][col] = sqrt(pow(Gx,2.0) + pow(Gy,2.0));   // Calculate gradient strength         
            thisAngle = (atan2(Gx,Gy)/3.14159) * 180.0;     // Calculate actual direction of edge
             
            /* Convert actual edge direction to approximate value */
            if ( ( (thisAngle < 22.5) && (thisAngle > -22.5) ) || (thisAngle > 157.5) || (thisAngle < -157.5) ) newAngle = 0; if ( ( (thisAngle > 22.5) && (thisAngle < 67.5) ) || ( (thisAngle < -112.5) && (thisAngle > -157.5) ) )
                newAngle = 45;
            if ( ( (thisAngle > 67.5) && (thisAngle < 112.5) ) || ( (thisAngle < -67.5) && (thisAngle > -112.5) ) )
                newAngle = 90;
            if ( ( (thisAngle > 112.5) && (thisAngle < 157.5) ) || ( (thisAngle < -22.5) && (thisAngle > -67.5) ) )
                newAngle = 135;
                 
            edgeDir[row][col] = newAngle;       // Store the approximate edge direction of each pixel in one array
        }
    }
 
    /* Trace along all the edges in the image */
    for (row = 1; row < H - 1; row++) {
        for (col = 1; col < W - 1; col++) { edgeEnd = false; if (gradient[row][col] > upperThreshold) {       // Check to see if current pixel has a high enough gradient strength to be part of an edge
                /* Switch based on current pixel's edge direction */
                switch (edgeDir[row][col]){    
                    case 0:
                        findEdge(0, 1, row, col, 0, lowerThreshold);
                        break;
                    case 45:
                        findEdge(1, 1, row, col, 45, lowerThreshold);
                        break;
                    case 90:
                        findEdge(1, 0, row, col, 90, lowerThreshold);
                        break;
                    case 135:
                        findEdge(1, -1, row, col, 135, lowerThreshold);
                        break;
                    default :
                        i = (unsigned long)(row*3*W + 3*col);
                        *(m_destinationBmp + i) =
                        *(m_destinationBmp + i + 1) =
                        *(m_destinationBmp + i + 2) = 0;
                        break;
                    }
                }
            else {
                i = (unsigned long)(row*3*W + 3*col);
                    *(m_destinationBmp + i) =
                    *(m_destinationBmp + i + 1) =
                    *(m_destinationBmp + i + 2) = 0;
            }  
        }
    }
     
    /* Suppress any pixels not changed by the edge tracing */
    for (row = 0; row < H; row++) {
        for (col = 0; col < W; col++) { 
            // Recall each pixel is composed of 3 bytes
            i = (unsigned long)(row*3*W + 3*col);
            // If a pixel's grayValue is not black or white make it black
            if( ((*(m_destinationBmp + i) != 255) && (*(m_destinationBmp + i) != 0)) || ((*(m_destinationBmp + i + 1) != 255) && (*(m_destinationBmp + i + 1) != 0)) || ((*(m_destinationBmp + i + 2) != 255) && (*(m_destinationBmp + i + 2) != 0)) )
                *(m_destinationBmp + i) =
                *(m_destinationBmp + i + 1) =
                *(m_destinationBmp + i + 2) = 0; // Make pixel black
        }
    }
 
    /* Non-maximum Suppression */
    for (row = 1; row < H - 1; row++) {
        for (col = 1; col < W - 1; col++) {
            i = (unsigned long)(row*3*W + 3*col);
            if (*(m_destinationBmp + i) == 255) {       // Check to see if current pixel is an edge
                /* Switch based on current pixel's edge direction */
                switch (edgeDir[row][col]) {       
                    case 0:
                        suppressNonMax( 1, 0, row, col, 0, lowerThreshold);
                        break;
                    case 45:
                        suppressNonMax( 1, -1, row, col, 45, lowerThreshold);
                        break;
                    case 90:
                        suppressNonMax( 0, 1, row, col, 90, lowerThreshold);
                        break;
                    case 135:
                        suppressNonMax( 1, 1, row, col, 135, lowerThreshold);
                        break;
                    default :
                        break;
                }
            }  
        }
    }
     
}
 
void CTripodDlg::findEdge(int rowShift, int colShift, int row, int col, int dir, int lowerThreshold)
{
    int W = 320;
    int H = 240;
    int newRow;
    int newCol;
    unsigned long i;
    bool edgeEnd = false;
 
    /* Find the row and column values for the next possible pixel on the edge */
    if (colShift < 0) { if (col > 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col < W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;     // If the next pixel would be off image, don't do the while loop
    if (rowShift < 0) { if (row > 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row < H - 1) { newRow = row + rowShift; } else edgeEnd = true; /* Determine edge directions and gradient strengths */ while ( (edgeDir[newRow][newCol]==dir) && !edgeEnd && (gradient[newRow][newCol] > lowerThreshold) ) {
        /* Set the new pixel as white to show it is an edge */
        i = (unsigned long)(newRow*3*W + 3*newCol);
        *(m_destinationBmp + i) =
        *(m_destinationBmp + i + 1) =
        *(m_destinationBmp + i + 2) = 255;
        if (colShift < 0) { if (newCol > 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol < W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift < 0) { if (newRow > 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow < H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
    }  
}
 
void CTripodDlg::suppressNonMax(int rowShift, int colShift, int row, int col, int dir, int lowerThreshold)
{
    int W = 320;
    int H = 240;
    int newRow = 0;
    int newCol = 0;
    unsigned long i;
    bool edgeEnd = false;
    float nonMax[320][3];           // Temporarily stores gradients and positions of pixels in parallel edges
    int pixelCount = 0;                 // Stores the number of pixels in parallel edges
    int count;                      // A for loop counter
    int max[3];                     // Maximum point in a wide edge
     
    if (colShift < 0) { if (col > 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col < W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;     // If the next pixel would be off image, don't do the while loop
    if (rowShift < 0) { if (row > 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row < H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
    i = (unsigned long)(newRow*3*W + 3*newCol);
    /* Find non-maximum parallel edges tracing up */
    while ((edgeDir[newRow][newCol] == dir) && !edgeEnd && (*(m_destinationBmp + i) == 255)) {
        if (colShift < 0) { if (newCol > 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol < W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift < 0) { if (newRow > 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow < H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
        nonMax[pixelCount][0] = newRow;
        nonMax[pixelCount][1] = newCol;
        nonMax[pixelCount][2] = gradient[newRow][newCol];
        pixelCount++;
        i = (unsigned long)(newRow*3*W + 3*newCol);
    }
 
    /* Find non-maximum parallel edges tracing down */
    edgeEnd = false;
    colShift *= -1;
    rowShift *= -1;
    if (colShift < 0) { if (col > 0)
            newCol = col + colShift;
        else
            edgeEnd = true;
    } else if (col < W - 1) {
        newCol = col + colShift;
    } else
        edgeEnd = true;
    if (rowShift < 0) { if (row > 0)
            newRow = row + rowShift;
        else
            edgeEnd = true;
    } else if (row < H - 1) {
        newRow = row + rowShift;
    } else
        edgeEnd = true;
    i = (unsigned long)(newRow*3*W + 3*newCol);
    while ((edgeDir[newRow][newCol] == dir) && !edgeEnd && (*(m_destinationBmp + i) == 255)) {
        if (colShift < 0) { if (newCol > 0)
                newCol = newCol + colShift;
            else
                edgeEnd = true;
        } else if (newCol < W - 1) {
            newCol = newCol + colShift;
        } else
            edgeEnd = true;
        if (rowShift < 0) { if (newRow > 0)
                newRow = newRow + rowShift;
            else
                edgeEnd = true;
        } else if (newRow < H - 1) {
            newRow = newRow + rowShift;
        } else
            edgeEnd = true;
        nonMax[pixelCount][0] = newRow;
        nonMax[pixelCount][1] = newCol;
        nonMax[pixelCount][2] = gradient[newRow][newCol];
        pixelCount++;
        i = (unsigned long)(newRow*3*W + 3*newCol);
    }
 
    /* Suppress non-maximum edges */
    max[0] = 0;
    max[1] = 0;
    max[2] = 0;
    for (count = 0; count < pixelCount; count++) { if (nonMax[count][2] > max[2]) {
            max[0] = nonMax[count][0];
            max[1] = nonMax[count][1];
            max[2] = nonMax[count][2];
        }
    }
    for (count = 0; count < pixelCount; count++) {
        i = (unsigned long)(nonMax[count][0]*3*W + 3*nonMax[count][1]);
        *(m_destinationBmp + i) =
        *(m_destinationBmp + i + 1) =
        *(m_destinationBmp + i + 2) = 0;
    }
}

الگوریتم Canny در سی پلاس پلاس قسمت 1
الگوریتم Canny در سی پلاس پلاس قسمت 2
الگوریتم Canny در سی پلاس پلاس قسمت 3
الگوریتم Canny در سی پلاس پلاس فسمت 4

الگوریتم Canny

لبه یاب کنی توسط جان اف کنی در سال 1986 ایجاد شد و هنوز یک لبه یاب استاندارد و با دقت و کیفیت بالا میباشد.الگوریتم لبه یابی کنی یکی از بهترین لبه یابها تا به امروز است. در ادامه روش کار این الگوریتم و هم چنین کد الگوریتم Canny در C را بررسی خواهیم کرد. این الگوریتم لبه یابی از سه بخش اصلی زیر تشکیل شده است:

  • تضعیف نویز
  • پیدا کردن نقاطی که بتوان آنها را به عنوان لبه در نظر گرفت
  • جذب نقاطی که احتمال لبه بودن آنها کم است

 

معیارهایی که در لبه یاب کنی مطرح می باشد:
1 -پایین آوردن نرخ خطا- یعنی تا حد امکان هیچ لبه ای در تصویر نباید گم شود و هم چنین هیچ چیزی که لبه نیست نباید به جای لبه فرض شود. لبه هان پیدا شده تا حد ممکن به لبه ها اصلی
نزدیک باشند.

2 -لبه در مکان واقعی خود باشد- یعنی تا حد ممکن لبه ها کمترین فاصله را با مکان واقعی خود داشته باشند.
3 -بران هر لبه فقط یک پاسخ داشته باشیم.

4 -لبه ها کمترین ضخامت را داشته باشند- (در صورت امکان یک پیکسل).
لبه یاب کنی بخاطر توانایی در تولید لبه های نازک تا حد یک ییکسل برای لبه های پیوسته معروف شده است. این لبه یاب شامل چهار مرحله و چهار ورودی زیر است:
یک تصویر ورودی
یک پارامتر به نام سیگما جهت مقدار نرم کنندگی تصویر
یک حد آستانه بالا (Th)
یک حد آستانه پایین (Tl)

 

مراحل الگوریتم Canny:

1- در ابتدا باید تصویر رنگی را به جهت لبه یابی بهتر به یک تصویر سطح خاکسترن تبدیب کرد.

2- نویز را از تصویر دریافتی حذف کرد. بدلیل اینکه فیلتر گاوسین از یک ماسک ساده برای حذف نویز استفاده می کند لبه یاب کنی در مرحله اول برای حذف نویز آن را بکار می گیرد.

3- در یک تصویر سطح خاکستر جایی را که بیشترین تغییرات را داشته باشند به عنوان لبه در نظر گرفته می شوند و این مکانها با گرفتن گرادیان تصویر با استفاده عملگر سوبل بدست می آیند. سپس لبه های مات یافت شده به لبه های تیزتر تبدیل می شوند.

4- برخی از لبه های کشف شده واقعا لبه نیستند و در واقع نویز هستند که باید آنها توسط حد آستانه هیسترزیس فیلتر شوند.هیسترزیس از دو حد آستانه بالاتر (Th) و حد آستانه پایین تر (Tl) استفاده کرده و کنی پیشنهاد می کند که نسبت استانه بالا به پایین سه به یک باشد.

 این روش بیشتر به کشف لبه های ضعیف به درستی می پردازد و کمتر فریب نویز را می خورد و از بقیه روش ها بهتر است.

 

الگوریتم Canny    عملکرد الگوریتم Canny

 

 

کد الگوریتم Canny در C :

برنامه زیر یک فایل BMP سیاه و سفید 8 بیت در هر پیکسل را می خواند و نتیجه را در ‘out.bmp’ ذخیره می کند.با `-lm ‘ کامپایل می شود.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
  
#define MAX_BRIGHTNESS 255
  
// C99 doesn't define M_PI (GNU-C99 does)
#define M_PI 3.14159265358979323846264338327
  
/*
 * Loading part taken from
 * BMP info:
 *
 * Note: the magic number has been removed from the bmpfile_header_t
 * structure since it causes alignment problems
 * bmpfile_magic_t should be written/read first
 * followed by the
 * bmpfile_header_t
 * [this avoids compiler-specific alignment pragmas etc.]
 */
  
typedef struct {
 uint8_t magic[2];
} bmpfile_magic_t;
  
typedef struct {
 uint32_t filesz;
 uint16_t creator1;
 uint16_t creator2;
 uint32_t bmp_offset;
} bmpfile_header_t;
  
typedef struct {
 uint32_t header_sz;
 int32_t width;
 int32_t height;
 uint16_t nplanes;
 uint16_t bitspp;
 uint32_t compress_type;
 uint32_t bmp_bytesz;
 int32_t hres;
 int32_t vres;
 uint32_t ncolors;
 uint32_t nimpcolors;
} bitmap_info_header_t;
  
typedef struct {
 uint8_t r;
 uint8_t g;
 uint8_t b;
 uint8_t nothing;
} rgb_t;
  
// Use short int instead `unsigned char' so that we can
// store negative values.
typedef short int pixel_t;
  
pixel_t *load_bmp(const char *filename,
 bitmap_info_header_t *bitmapInfoHeader)
{
 FILE *filePtr = fopen(filename, "rb");
 if (filePtr == NULL) {
 perror("fopen()");
 return NULL;
 }
  
 bmpfile_magic_t mag;
 if (fread(&mag, sizeof(bmpfile_magic_t), 1, filePtr) != 1) {
 fclose(filePtr);
 return NULL;
 }
  
 // verify that this is a bmp file by check bitmap id
 // warning: dereferencing type-punned pointer will break
 // strict-aliasing rules [-Wstrict-aliasing]
 if (*((uint16_t*)mag.magic) != 0x4D42) {
 fprintf(stderr, "Not a BMP file: magic=%c%c\n",
 mag.magic[0], mag.magic[1]);
 fclose(filePtr);
 return NULL;
 }
  
 bmpfile_header_t bitmapFileHeader; // our bitmap file header
 // read the bitmap file header
 if (fread(&bitmapFileHeader, sizeof(bmpfile_header_t),
 1, filePtr) != 1) {
 fclose(filePtr);
 return NULL;
 }
  
 // read the bitmap info header
 if (fread(bitmapInfoHeader, sizeof(bitmap_info_header_t),
 1, filePtr) != 1) {
 fclose(filePtr);
 return NULL;
 }
  
 if (bitmapInfoHeader->compress_type != 0)
 fprintf(stderr, "Warning, compression is not supported.\n");
  
 // move file point to the beginning of bitmap data
 if (fseek(filePtr, bitmapFileHeader.bmp_offset, SEEK_SET)) {
 fclose(filePtr);
 return NULL;
 }
  
 // allocate enough memory for the bitmap image data
 pixel_t *bitmapImage = malloc(bitmapInfoHeader->bmp_bytesz *
 sizeof(pixel_t));
  
 // verify memory allocation
 if (bitmapImage == NULL) {
 fclose(filePtr);
 return NULL;
 }
  
 // read in the bitmap image data
 size_t pad, count=0;
 unsigned char c;
 pad = 4*ceil(bitmapInfoHeader->bitspp*bitmapInfoHeader->width/32.) - bitmapInfoHeader->width;
 for(size_t i=0; i<bitmapInfoHeader->height; i++){
 for(size_t j=0; j<bitmapInfoHeader->width; j++){
 if (fread(&c, sizeof(unsigned char), 1, filePtr) != 1) {
 fclose(filePtr);
 return NULL;
 }
 bitmapImage[count++] = (pixel_t) c;
 }
 fseek(filePtr, pad, SEEK_CUR);
 }
  
 // If we were using unsigned char as pixel_t, then:
 // fread(bitmapImage, 1, bitmapInfoHeader->bmp_bytesz, filePtr);
  
 // close file and return bitmap image data
 fclose(filePtr);
 return bitmapImage;
}
  
// Return: true on error.
bool save_bmp(const char *filename, const bitmap_info_header_t *bmp_ih,
 const pixel_t *data)
{
 FILE* filePtr = fopen(filename, "wb");
 if (filePtr == NULL)
 return true;
  
 bmpfile_magic_t mag = {{0x42, 0x4d}};
 if (fwrite(&mag, sizeof(bmpfile_magic_t), 1, filePtr) != 1) {
 fclose(filePtr);
 return true;
 }
  
 const uint32_t offset = sizeof(bmpfile_magic_t) +
 sizeof(bmpfile_header_t) +
 sizeof(bitmap_info_header_t) +
 ((1U << bmp_ih->bitspp) * 4);
  
 const bmpfile_header_t bmp_fh = {
 .filesz = offset + bmp_ih->bmp_bytesz,
 .creator1 = 0,
 .creator2 = 0,
 .bmp_offset = offset
 };
  
 if (fwrite(&bmp_fh, sizeof(bmpfile_header_t), 1, filePtr) != 1) {
 fclose(filePtr);
 return true;
 }
 if (fwrite(bmp_ih, sizeof(bitmap_info_header_t), 1, filePtr) != 1) {
 fclose(filePtr);
 return true;
 }
  
 // Palette
 for (size_t i = 0; i < (1U << bmp_ih->bitspp); i++) {
 const rgb_t color = {(uint8_t)i, (uint8_t)i, (uint8_t)i};
 if (fwrite(&color, sizeof(rgb_t), 1, filePtr) != 1) {
 fclose(filePtr);
 return true;
 }
 }
  
 // We use int instead of uchar, so we can't write img
 // in 1 call any more.
 // fwrite(data, 1, bmp_ih->bmp_bytesz, filePtr);
  
 size_t pad = 4*ceil(bmp_ih->bitspp*bmp_ih->width/32.) - bmp_ih->width;
 unsigned char c;
 for(size_t i=0; i < bmp_ih->height; i++) {
 for(size_t j=0; j < bmp_ih->width; j++) {
 c = (unsigned char) data[j + bmp_ih->width*i];
 if (fwrite(&c, sizeof(char), 1, filePtr) != 1) {
 fclose(filePtr);
 return true;
 }
 }
 c = 0;
 for(size_t j=0; j<pad; j++)
 if (fwrite(&c, sizeof(char), 1, filePtr) != 1) {
 fclose(filePtr);
 return true;
 }
 }
  
 fclose(filePtr);
 return false;
}
  
// if normalize is true, map pixels to range 0..MAX_BRIGHTNESS
void convolution(const pixel_t *in, pixel_t *out, const float *kernel,
 const int nx, const int ny, const int kn,
 const bool normalize)
{
 assert(kn % 2 == 1);
 assert(nx > kn && ny > kn);
 const int khalf = kn / 2;
 float min = FLT_MAX, max = -FLT_MAX;
  
 if (normalize)
 for (int m = khalf; m < nx - khalf; m++)
 for (int n = khalf; n < ny - khalf; n++) {
 float pixel = 0.0;
 size_t c = 0;
 for (int j = -khalf; j <= khalf; j++)
 for (int i = -khalf; i <= khalf; i++) {
 pixel += in[(n - j) * nx + m - i] * kernel;
 c++;
 }
 if (pixel < min)
 min = pixel;
 if (pixel > max)
 max = pixel;
 }
  
 for (int m = khalf; m < nx - khalf; m++)
 for (int n = khalf; n < ny - khalf; n++) {
 float pixel = 0.0;
 size_t c = 0;
 for (int j = -khalf; j <= khalf; j++)
 for (int i = -khalf; i <= khalf; i++) {
 pixel += in[(n - j) * nx + m - i] * kernel;
 c++;
 }
  
 if (normalize)
 pixel = MAX_BRIGHTNESS * (pixel - min) / (max - min);
 out[n * nx + m] = (pixel_t)pixel;
 }
}
  
/*
 * gaussianFilter:
 * determine size of kernel (odd #)
 * 0.0 <= sigma < 0.5 : 3
 * 0.5 <= sigma < 1.0 : 5
 * 1.0 <= sigma < 1.5 : 7
 * 1.5 <= sigma < 2.0 : 9
 * 2.0 <= sigma < 2.5 : 11
 * 2.5 <= sigma < 3.0 : 13 ...
 * kernelSize = 2 * int(2*sigma) + 3;
 */
void gaussian_filter(const pixel_t *in, pixel_t *out,
 const int nx, const int ny, const float sigma)
{
 const int n = 2 * (int)(2 * sigma) + 3;
 const float mean = (float)floor(n / 2.0);
 float kernel[n * n]; // variable length array
  
 fprintf(stderr, "gaussian_filter: kernel size %d, sigma=%g\n",
 n, sigma);
 size_t c = 0;
 for (int i = 0; i < n; i++)
 for (int j = 0; j < n; j++) {
 kernel = exp(-0.5 * (pow((i - mean) / sigma, 2.0) +
 pow((j - mean) / sigma, 2.0)))
 / (2 * M_PI * sigma * sigma);
 c++;
 }
  
 convolution(in, out, kernel, nx, ny, n, true);
}
  
/*
 * Links:
 *
 * Note: T1 and T2 are lower and upper thresholds.
 */
pixel_t *canny_edge_detection(const pixel_t *in,
 const bitmap_info_header_t *bmp_ih,
 const int tmin, const int tmax,
 const float sigma)
{
 const int nx = bmp_ih->width;
 const int ny = bmp_ih->height;
  
 pixel_t *G = calloc(nx * ny * sizeof(pixel_t), 1);
 pixel_t *after_Gx = calloc(nx * ny * sizeof(pixel_t), 1);
 pixel_t *after_Gy = calloc(nx * ny * sizeof(pixel_t), 1);
 pixel_t *nms = calloc(nx * ny * sizeof(pixel_t), 1);
 pixel_t *out = malloc(bmp_ih->bmp_bytesz * sizeof(pixel_t));
  
 if (G == NULL || after_Gx == NULL || after_Gy == NULL ||
 nms == NULL || out == NULL) {
 fprintf(stderr, "canny_edge_detection:"
 " Failed memory allocation(s).\n");
 exit(1);
 }
  
 gaussian_filter(in, out, nx, ny, sigma);
  
 const float Gx[] = {-1, 0, 1,
 -2, 0, 2,
 -1, 0, 1};
  
 convolution(out, after_Gx, Gx, nx, ny, 3, false);
  
 const float Gy[] = { 1, 2, 1,
 0, 0, 0,
 -1,-2,-1};
  
 convolution(out, after_Gy, Gy, nx, ny, 3, false);
  
 for (int i = 1; i < nx - 1; i++)
 for (int j = 1; j < ny - 1; j++) {
 const int c = i + nx * j;
 // G = abs(after_Gx) + abs(after_Gy);
 G = (pixel_t)hypot(after_Gx, after_Gy);
 }
  
 // Non-maximum suppression, straightforward implementation.
 for (int i = 1; i < nx - 1; i++)
 for (int j = 1; j < ny - 1; j++) {
 const int c = i + nx * j;
 const int nn = c - nx;
 const int ss = c + nx;
 const int ww = c + 1;
 const int ee = c - 1;
 const int nw = nn + 1;
 const int ne = nn - 1;
 const int sw = ss + 1;
 const int se = ss - 1;
  
 const float dir = (float)(fmod(atan2(after_Gy,
 after_Gx) + M_PI,
 M_PI) / M_PI) * 8;
  
 if (((dir <= 1 || dir > 7) && G > G[ee] &&
 G > G[ww]) || // 0 deg
 ((dir > 1 && dir <= 3) && G > G[nw] &&
 G > G[se]) || // 45 deg
 ((dir > 3 && dir <= 5) && G > G[nn] &&
 G > G[ss]) || // 90 deg
 ((dir > 5 && dir <= 7) && G > G[ne] &&
 G > G[sw])) // 135 deg
 nms = G;
 else
 nms = 0;
 }
  
 // Reuse array
 // used as a stack. nx*ny/2 elements should be enough.
 int *edges = (int*) after_Gy;
 memset(out, 0, sizeof(pixel_t) * nx * ny);
 memset(edges, 0, sizeof(pixel_t) * nx * ny);
  
 // Tracing edges with hysteresis . Non-recursive implementation.
 size_t c = 1;
 for (int j = 1; j < ny - 1; j++)
 for (int i = 1; i < nx - 1; i++) {
 if (nms >= tmax && out == 0) { // trace edges
 out = MAX_BRIGHTNESS;
 int nedges = 1;
 edges[0] = c;
  
 do {
 nedges--;
 const int t = edges[nedges];
  
 int nbs[8]; // neighbours
 nbs[0] = t - nx; // nn
 nbs[1] = t + nx; // ss
 nbs[2] = t + 1; // ww
 nbs[3] = t - 1; // ee
 nbs[4] = nbs[0] + 1; // nw
 nbs[5] = nbs[0] - 1; // ne
 nbs[6] = nbs[1] + 1; // sw
 nbs[7] = nbs[1] - 1; // se
  
 for (int k = 0; k < 8; k++)
 if (nms[nbs[k]] >= tmin && out[nbs[k]] == 0) {
 out[nbs[k]] = MAX_BRIGHTNESS;
 edges[nedges] = nbs[k];
 nedges++;
 }
 } while (nedges > 0);
 }
 c++;
 }
  
 free(after_Gx);
 free(after_Gy);
 free(G);
 free(nms);
  
 return out;
}
  
int main(const int argc, const char ** const argv)
{
 if (argc < 2) {
 printf("Usage: %s image.bmp\n", argv[0]);
 return 1;
 }
  
 static bitmap_info_header_t ih;
 const pixel_t *in_bitmap_data = load_bmp(argv[1], &ih);
 if (in_bitmap_data == NULL) {
 fprintf(stderr, "main: BMP image not loaded.\n");
 return 1;
 }
  
 printf("Info: %d x %d x %d\n", ih.width, ih.height, ih.bitspp);
  
 const pixel_t *out_bitmap_data =
 canny_edge_detection(in_bitmap_data, &ih, 45, 50, 1.0f);
 if (out_bitmap_data == NULL) {
 fprintf(stderr, "main: failed canny_edge_detection.\n");
 return 1;
 }
  
 if (save_bmp("out.bmp", &ih, out_bitmap_data)) {
 fprintf(stderr, "main: BMP image not saved.\n");
 return 1;
 }
  
 free((pixel_t*)in_bitmap_data);
 free((pixel_t*)out_bitmap_data);
 return 0;
}

 

دانلود کد فوق از طریق لینک زیر:

Canny in C

رمز فایل : behsanandish.com

الگوریتم Canny

لبه یاب کنی توسط جان اف کنی در سال 1986 ایجاد شد و هنوز یک لبه یاب استاندارد و با دقت و کیفیت بالا میباشد.الگوریتم لبه یابی کنی یکی از بهترین لبه یابها تا به امروز است. در ادامه روش کار این الگوریتم و هم چنین کد الگوریتم Canny در OpenCV را بررسی خواهیم کرد. این الگوریتم لبه یابی از سه بخش اصلی زیر تشکیل شده:

  • تضعیف نویز
  • پیدا کردن نقاطی که بتوان آنها را به عنوان لبه در نظر گرفت
  • حذب نقاطی که احتمال لبه بودن آنها کم است

 

معیارهایی که در لبه یاب کنی مطرح است:
1 -پایین آوردن نرخ خطا- یعنی تا حد امکان هیچ لبه ای در تصویر نباید گم شود و هم چنین هیچ چیزی که لبه نیست نباید به جای لبه فرض شود. لبه هان پیدا شده تا حد ممکن به لبه ها اصلی
نزدیک باشند.

2 -لبه در مکان واقعی خود باشد- یعنی تا حد ممکن لبه ها کمترین فاصله را با مکان واقعی خود داشته باشند.
3 -بران هر لبه فقط یک پاسخ داشته باشیم.

4 -لبه ها کمترین ضخامت را داشته باشند- (در صورت امکان یک پیکسل).
لبه یاب کنی بخاطر توانایی در تولید لبه های نازک تا حد یک ییکسل برای لبه های پیوسته معروف شده است. این لبه یاب شامل چهار مرحله و چهار ورودی زیر است:
یک تصویر ورودی
یک پارامتر به نام سیگما جهت مقدار نرم کنندگی تصویر
یک حد آستانه بالا (Th)
یک حد آستانه پایین (Tl)

 

مراحل الگوریتم Canny:

1- در ابتدا باید تصویر رنگی را به جهت لبه یابی بهتر به یک تصویر سطح خاکسترن تبدیب کرد.

2- نویز را از تصویر دریافتی حذف کرد. بدلیل اینکه فیلتر گاوسین از یک ماسک ساده برای حذف نویز استفاده می کند لبه یاب کنی در مرحله اول برای حذف نویز آن را بکار میگیرد.

3- در یک تصویر سطح خاکستر جایی را که بیشترین تغییرات را داشته باشند به عنوان لبه در نظر گرفته می شوند و این مکانها با گرفتن گرادیان تصویر با استفاده عملگر سوبل بدست می آیند. سپس لبه های مات یافت شده به لبه های تیزتر تبدیل می شوند.

4- برخی از لبه های کشف شده واقعا لبه نیستند و در واقع نویز هستند که باید آنها توسط حد آستانه هیسترزیس فیلتر شوند.هیسترزیس از دو حد آستانه بالاتر (Th) و حد آستانه پایین تر (Tl) استفاده کرده و کنی پیشنهاد می کند که نسبت استانه بالا به پایین سه به یک باشد.

 این روش بیشتر به کشف لبه های ضعیف به درستی می پردازد و کمتر فریب نویز را می خورد و از بقیه روش ها بهتر است.

 

 

الگوریتم Canny    عملکرد الگوریتم Canny

 

کد الگوریتم Canny در OpenCV:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
 
using namespace cv;
 
/// Global variables
 
Mat src, src_gray;
Mat dst, detected_edges;
 
int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";
 
/**
 * @function CannyThreshold
 * @brief Trackbar callback - Canny thresholds input with a ratio 1:3
 */
void CannyThreshold(int, void*)
{
  /// Reduce noise with a kernel 3x3
  blur( src_gray, detected_edges, Size(3,3) );
 
  /// Canny detector
  Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );
 
  /// Using Canny's output as a mask, we display our result
  dst = Scalar::all(0);
 
  src.copyTo( dst, detected_edges);
  imshow( window_name, dst );
 }
 
/** @function main */
int main( int argc, char** argv )
{
  /// Load an image
  src = imread( argv[1] );
 
  if( !src.data )
  { return -1; }</pre>
<pre>  /// Create a matrix of the same type and size as src (for dst)
  dst.create( src.size(), src.type() );
 
  /// Convert the image to grayscale
  cvtColor( src, src_gray, CV_BGR2GRAY );
 
  /// Create a window
  namedWindow( window_name, CV_WINDOW_AUTOSIZE );
 
  /// Create a Trackbar for user to enter threshold
  createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
 
  /// Show the image
  CannyThreshold(0, 0);
 
  /// Wait until user exit program by pressing a key
  waitKey(0);
 
  return 0;
  }

 

 

دانلود کد فوق از طریق لینک زیر:

CannyInOpenCV

رمز فایل : behsanandish.com

 

الگوریتم Canny

لبه یاب کنی توسط جان اف کنی در سال 1986 ایجاد شد و هنوز یک لبه یاب استاندارد و با دقت و کیفیت بالا میباشد.الگوریتم لبه یابی کنی یکی از بهترین لبه یابها تا به امروز است. در ادامه روش کار این الگوریتم و هم چنین کد الگوریتم Canny در #C را بررسی خواهیم کرد. این الگوریتم لبه یابی از سه بخش اصلی زیر تشکیل شده:

  • تضعیف نویز
  • پیدا کردن نقاطی که بتوان آنها را به عنوان لبه در نظر گرفت
  • حذب نقاطی که احتمال لبه بودن آنها کم است

 

معیارهایی که در لبه یاب کنی مطرح است:
1 -پایین آوردن نرخ خطا- یعنی تا حد امکان هیچ لبه ای در تصویر نباید گم شود و هم چنین هیچ چیزی که لبه نیست نباید به جای لبه فرض شود. لبه هان پیدا شده تا حد ممکن به لبه ها اصلی
نزدیک باشند.

2 -لبه در مکان واقعی خود باشد- یعنی تا حد ممکن لبه ها کمترین فاصله را با مکان واقعی خود داشته باشند.
3 -بران هر لبه فقط یک پاسخ داشته باشیم.

4 -لبه ها کمترین ضخامت را داشته باشند- (در صورت امکان یک پیکسل).
لبه یاب کنی بخاطر توانایی در تولید لبه های نازک تا حد یک ییکسل برای لبه های پیوسته معروف شده است. این لبه یاب شامل چهار مرحله و چهار ورودی زیر است:
یک تصویر ورودی
یک پارامتر به نام سیگما جهت مقدار نرم کنندگی تصویر
یک حد آستانه بالا (Th)
یک حد آستانه پایین (Tl)

 

مراحل الگوریتم Canny:

1- در ابتدا باید تصویر رنگی را به جهت لبه یابی بهتر به یک تصویر سطح خاکسترن تبدیب کرد.

2- نویز را از تصویر دریافتی حذف کرد. بدلیل اینکه فیلتر گاوسین از یک ماسک ساده برای حذف نویز استفاده می کند لبه یاب کنی در مرحله اول برای حذف نویز آن را بکار میگیرد.

3- در یک تصویر سطح خاکستر جایی را که بیشترین تغییرات را داشته باشند به عنوان لبه در نظر گرفته می شوند و این مکانها با گرفتن گرادیان تصویر با استفاده عملگر سوبل بدست می آیند. سپس لبه های مات یافت شده به لبه های تیزتر تبدیل می شوند.

4- برخی از لبه های کشف شده واقعا لبه نیستند و در واقع نویز هستند که باید آنها توسط حد آستانه هیسترزیس فیلتر شوند.هیسترزیس از دو حد آستانه بالاتر (Th) و حد آستانه پایین تر (Tl) استفاده کرده و کنی پیشنهاد می کند که نسبت استانه بالا به پایین سه به یک باشد.

 این روش بیشتر به کشف لبه های ضعیف به درستی می پردازد و کمتر فریب نویز را می خورد و از بقیه روش ها بهتر است.

 

الگوریتم Canny    عملکرد الگوریتم Canny

 


 

کد الگوریتم Canny در #C:

الگوریتم در 5 مرحله جداگانه اجرا می شود:

1. صاف کردن: تار شدن تصویر برای حذف نویز. پیکربندی توسط فیلتر گاوسی با اندازه مشخص هسته (N) و پارامتر پوشش گاوسی سیگما. پوشاننده فیلتر گاوسی توسط تابع زیر تولید می شود:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
private void GenerateGaussianKernel(int N, float S ,out int Weight)
{
 
float Sigma = S ;
float pi;
pi = (float)Math.PI;
int i, j;
int SizeofKernel=N;
 
float [,] Kernel = new float [N,N];
GaussianKernel = new int [N,N];
float[,] OP = new float[N, N];
float D1,D2;
 
D1= 1/(2*pi*Sigma*Sigma);
D2= 2*Sigma*Sigma;
 
float min=1000;
 
for (i = -SizeofKernel / 2; i <= SizeofKernel / 2; i++)
{
for (j = -SizeofKernel / 2; j <= SizeofKernel / 2; j++)
{
Kernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j] = ((1 / D1) * (float)Math.Exp(-(i * i + j * j) / D2));
if (Kernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j] < min)
min = Kernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j];
 
}
}
int mult = (int)(1 / min);
int sum = 0;
if ((min > 0) && (min < 1))
{
 
for (i = -SizeofKernel / 2; i <= SizeofKernel / 2; i++)
{
for (j = -SizeofKernel / 2; j <= SizeofKernel / 2; j++)
{
Kernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j] = (float)Math.Round(Kernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j] * mult, 0);
GaussianKernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j] = (int)Kernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j];
sum = sum + GaussianKernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j];
}
 
}
 
}
else
{
sum = 0;
for (i = -SizeofKernel / 2; i <= SizeofKernel / 2; i++)
{
for (j = -SizeofKernel / 2; j <= SizeofKernel / 2; j++)
{
Kernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j] = (float)Math.Round(Kernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j] , 0);
GaussianKernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j] = (int)Kernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j];
sum = sum + GaussianKernel[SizeofKernel / 2 + i, SizeofKernel / 2 + j];
}
 
}
 
}
//Normalizing kernel Weight
Weight= sum;
 
return;
}

 

زیر روال ذیل نویز را توسط فیلتر گوسی حذف می کند.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private int[,] GaussianFilter(int[,] Data)
        {
            GenerateGaussianKernel(KernelSize, Sigma,out KernelWeight);
 
            int[,] Output = new int[Width, Height];
            int i, j,k,l;
            int Limit = KernelSize /2;
 
            float Sum=0;
 
 Output = Data; // Removes Unwanted Data Omission due to kernel bias while convolution
 
            for (i = Limit; i <= ((Width - 1) - Limit); i++)
            {
                for (j = Limit; j <= ((Height - 1) - Limit); j++)
                {
                    Sum = 0;
                    for (k = -Limit; k <= Limit; k++)
                    {
 
                       for (l = -Limit; l <= Limit; l++)
                        {
                            Sum = Sum + ((float)Data[i + k, j + l] * GaussianKernel [Limit + k, Limit + l]);                        
 
                        }
                    }
                    Output[i, j] = (int)(Math.Round(Sum/ (float)KernelWeight));
                }
 
            }
 
            return Output;
        }

 

2. پیدا کردن شیب ها: لبه ها باید مشخص شوند، جایی که شیب های تصویر بزرگ می شوند.

ماسک های سوبل  X و Y برای تولید گرادیان های تصویر X و Y استفاده می شود؛ تابع بعدی تمایز را با استفاده از فیلتر ماسک sobel اعمال می کند.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private float[,] Differentiate(int[,] Data, int[,] Filter)
        {
            int i, j,k,l, Fh, Fw;
 
            Fw = Filter.GetLength(0);
            Fh = Filter.GetLength(1);
            float sum = 0;
            float[,] Output = new float[Width, Height];
 
            for (i = Fw / 2; i <= (Width - Fw / 2) - 1; i++)
            {
                for (j = Fh / 2; j <= (Height  - Fh / 2) - 1; j++)
                {
                  sum=0;
                   for(k=-Fw/2; k<=Fw/2; k++)
                   {
                       for(l=-Fh/2; l<=Fh/2; l++)
                       {
                          sum=sum + Data[i+k,j+l]*Filter[Fw/2+k,Fh/2+l];
 
 
                       }
                   }
                    Output[i,j]=sum;
 
                }
 
            }
            return Output;
 
        }

 

3. توقیف غیر حداکثر: فقط حداکثرهای محلی باید به عنوان لبه ها مشخص شود.

ما جهت گرادیان را پیدا می کنیم و با استفاده از این جهت، ما توقیف غیر حداکثر را انجام می دهیم (“پردازش تصویر دیجیتال- آموزش توسط گنزالس-پیرسون ” را بخوانید)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Perform Non maximum suppression:
           // NonMax = Gradient;
 
            for (i = 0; i <= (Width - 1); i++)
            {
                for (j = 0; j <= (Height - 1); j++)
                {
                    NonMax[i, j] = Gradient[i, j];
                }
            }
      
            int Limit = KernelSize / 2;
            int r, c;
            float Tangent;
 
                for (i = Limit; i <= (Width - Limit) - 1; i++)
            {
                for (j = Limit; j <= (Height - Limit) - 1; j++)
                {
 
                    if (DerivativeX[i, j] == 0)
                        Tangent = 90F;
                    else
                        Tangent = (float)(Math.Atan(DerivativeY[i, j] / DerivativeX[i, j]) * 180 / Math.PI); //rad to degree
 
 
 
                    //Horizontal Edge
                    if (((-22.5 < Tangent) && (Tangent <= 22.5)) || ((157.5 < Tangent) && (Tangent <= -157.5)))
                    {
                        if ((Gradient[i, j] < Gradient[i, j + 1]) || (Gradient[i, j] < Gradient[i, j - 1]))
                            NonMax[i, j] = 0;
                    }
 
                    //Vertical Edge
                    if (((-112.5 < Tangent) && (Tangent <= -67.5)) || ((67.5 < Tangent) && (Tangent <= 112.5)))
                    {
                        if ((Gradient[i, j] < Gradient[i + 1, j]) || (Gradient[i, j] < Gradient[i - 1, j]))
                            NonMax[i, j] = 0;
                    }
 
                    //+45 Degree Edge
                    if (((-67.5 < Tangent) && (Tangent <= -22.5)) || ((112.5 < Tangent) && (Tangent <= 157.5)))
                    {
                        if ((Gradient[i, j] < Gradient[i + 1, j - 1]) || (Gradient[i, j] < Gradient[i - 1, j + 1]))
                            NonMax[i, j] = 0;
                    }
 
                    //-45 Degree Edge
                    if (((-157.5 < Tangent) && (Tangent <= -112.5)) || ((67.5 < Tangent) && (Tangent <= 22.5)))
                    {
                        if ((Gradient[i, j] < Gradient[i + 1, j + 1]) || (Gradient[i, j] < Gradient[i - 1, j - 1]))
                            NonMax[i, j] = 0;
                    }
 
                }
 
            }

 

4. آستانه دوگانه: لبه های بالقوه توسط آستانه تعیین می شود.

5. ردیابی لبه توسط هیسترسیس: لبه های نهایی توسط توقیف تمام لبه هایی که به یک لبه بسیار قطعی (قوی) متصل نیستند، مشخص می شوند.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
private void HysterisisThresholding(int[,] Edges)
        {
 
            int i, j;
            int Limit= KernelSize/2;
 
 
            for (i = Limit; i <= (Width - 1) - Limit; i++)
                for (j = Limit; j <= (Height - 1) - Limit; j++)
                {
                    if (Edges[i, j] == 1)
                    {
                        EdgeMap[i, j] = 1;
 
                    }
 
                }
 
            for (i = Limit; i <= (Width - 1) - Limit; i++)
            {
                for (j = Limit; j <= (Height  - 1) - Limit; j++)
                {
                    if (Edges[i, j] == 1)
                    {
                        EdgeMap[i, j] = 1;
                        Travers(i, j);
                        VisitedMap[i, j] = 1;
                    }
                }
            }
 
 
 
 
            return;
        }
 
//Recursive Procedure 
private void Travers(int X, int Y)
        {
 
             
            if (VisitedMap[X, Y] == 1)
            {
                return;
            }
 
            //1
            if (EdgePoints[X + 1, Y] == 2)
            {
                EdgeMap[X + 1, Y] = 1;
                VisitedMap[X + 1, Y] = 1;
                Travers(X + 1, Y);
                return;
            }
            //2
            if (EdgePoints[X + 1, Y - 1] == 2)
            {
                EdgeMap[X + 1, Y - 1] = 1;
                VisitedMap[X + 1, Y - 1] = 1;
                Travers(X + 1, Y - 1);
                return;
            }
 
           //3
 
            if (EdgePoints[X, Y - 1] == 2)
            {
                EdgeMap[X , Y - 1] = 1;
                VisitedMap[X , Y - 1] = 1;
                Travers(X , Y - 1);
                return;
            }
 
           //4
 
            if (EdgePoints[X - 1, Y - 1] == 2)
            {
                EdgeMap[X - 1, Y - 1] = 1;
                VisitedMap[X - 1, Y - 1] = 1;
                Travers(X - 1, Y - 1);
                return;
            }
            //5
            if (EdgePoints[X - 1, Y] == 2)
            {
                EdgeMap[X - 1, Y ] = 1;
                VisitedMap[X - 1, Y ] = 1;
                Travers(X - 1, Y );
                return;
            }
            //6
            if (EdgePoints[X - 1, Y + 1] == 2)
            {
                EdgeMap[X - 1, Y + 1] = 1;
                VisitedMap[X - 1, Y + 1] = 1;
                Travers(X - 1, Y + 1);
                return;
            }
            //7
            if (EdgePoints[X, Y + 1] == 2)
            {
                EdgeMap[X , Y + 1] = 1;
                VisitedMap[X, Y + 1] = 1;
                Travers(X , Y + 1);
                return;
            }
            //8
 
            if (EdgePoints[X + 1, Y + 1] == 2)
            {
                EdgeMap[X + 1, Y + 1] = 1;
                VisitedMap[X + 1, Y + 1] = 1;
                Travers(X + 1, Y + 1);
                return;
            }
 
 
            //VisitedMap[X, Y] = 1;
            return;
 
        }
           
        //Canny Class Ends
 
    }

 

این کار با یک تابع بازگشتی انجام می شود که آستانه دوگانه را با دو آستانه بالا (Threshold (TH و (Low Threshold (TL و تجزیه و تحلیل 8-اتصال انجام می دهد.

 

دانلود کد فوق از طریق لینک زیر:

Canny Edge Detection C#

رمز فایل : behsanandish.com


الگوریتم Canny

لبه یاب کنی توسط جان اف کنی در سال 1986 ایجاد شد و هنوز یک لبه یاب استاندارد و با دقت و کیفیت بالا میباشد.الگوریتم لبه یابی کنی یکی از بهترین لبه یابها تا به امروز است. در ادامه روش کار این الگوریتم و هم چنین کد الگوریتم Canny در Visual Basic را بررسی خواهیم کرد. این الگوریتم لبه یابی از سه بخش اصلی زیر تشکیل شده:

  • تضعیف نویز
  • پیدا کردن نقاطی که بتوان آنها را به عنوان لبه در نظر گرفت
  • حذب نقاطی که احتمال لبه بودن آنها کم است

 

معیارهایی که در لبه یا کنی مطرح است:
1 -پایین آوردن نرخ خطا- یعنی تا حد امکان هیچ لبه ای در تصویر نباید گم شود و هم چنین هیچ چیزی که لبه نیست نباید به جای لبه فرض شود. لبه هان پیدا شده تا حد ممکن به لبه ها اصلی
نزدیک باشند.

2 -لبه در مکان واقعی خود باشد- یعنی تا حد ممکن لبه ها کمترین فاصله را با مکان واقعی خود داشته باشند.
3 -بران هر لبه فقط یک پاسخ داشته باشیم.

4 -لبه ها کمترین ضخامت را داشته باشند- (در صورت امکان یک پیکسل).
لبه یاب کنی بخاطر توانایی در تولید لبه های نازک تا حد یک ییکسل برای لبه های پیوسته معروف شده است. این لبه یاب شامل چهار مرحله و چهار ورودی زیر است:
یک تصویر ورودی
یک پارامتر به نام سیگما جهت مقدار نرم کنندگی تصویر
یک حد آستانه بالا (Th)
یک حد آستانه پایین (Tl)

 

مراحل الگوریتم Canny:

1- در ابتدا باید تصویر رنگی را به جهت لبه یابی بهتر به یک تصویر سطح خاکسترن تبدیب کرد.

2- نویز را از تصویر دریافتی حذف کرد. بدلیل اینکه فیلتر گاوسین از یک ماسک ساده برای حذف نویز استفاده می کند لبه یاب کنی در مرحله اول برای حذف نویز آن را بکار میگیرد.

3- در یک تصویر سطح خاکستر جایی را که بیشترین تغییرات را داشته باشند به عنوان لبه در نظر گرفته می شوند و این مکانها با گرفتن گرادیان تصویر با استفاده عملگر سوبل بدست می آیند. سپس لبه های مات یافت شده به لبه های تیزتر تبدیل می شوند.

4- برخی از لبه های کشف شده واقعا لبه نیستند و در واقع نویز هستند که باید آنها توسط حد آستانه هیسترزیس فیلتر شوند.هیسترزیس از دو حد آستانه بالاتر (Th) و حد آستانه پایین تر (Tl) استفاده کرده و کنی پیشنهاد می کند که نسبت استانه بالا به پایین سه به یک باشد.

 این روش بیشتر به کشف لبه های ضعیف به درستی می پردازد و کمتر فریب نویز را می خورد و از بقیه روش ها بهتر است.

 

الگوریتم Canny    عملکرد الگوریتم Canny

 

الگوریتم Canny در Visual Basic:

کد زیر یک کد تکمیل نشده است.تکمیل آن به عنوان تمرین به خواننده واگذار می شود.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
Imports System.Drawing
Imports System.Drawing.Imaging
 
Public Class clsEdges
 
    Public Sub EdgeDetectDifference(ByVal b As Bitmap, ByVal threshold As Byte)
        ' first we create a clone o the image we want to find the edges on
        Dim b2 As Bitmap = b.Clone
        ' we create bitmapdata of the images at the same time locking them
        Dim bmData1 As BitmapData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
        Dim bmData2 As BitmapData = b2.LockBits(New Rectangle(0, 0, b2.Width, b2.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
        ' the stride describes the distance between image bytes
        Dim stride As Integer = bmData2.Stride
        ' scan0 is some sort of OS handle or something to identify the actual data in the memory
        Dim scan01 As IntPtr = bmData1.Scan0
        Dim scan02 As IntPtr = bmData2.Scan0
        ' we need to know how big the data is so that we can create the correct size for the file
        Dim bytes As Integer = b.Height * b.Width * 3
        ' we create the byte arrays so that we can edit them
        Dim p01(bytes - 1) As Byte
        Dim p02(bytes - 1) As Byte
        ' put the images into the byte arrays
        System.Runtime.InteropServices.Marshal.Copy(scan01, p01, 0, bytes)
        System.Runtime.InteropServices.Marshal.Copy(scan02, p02, 0, bytes)
 
        ' the nWidth describes the width of the actual image multiplied by three for each byte in the pixel (3 bytes per pixel 24 bits ;))
        Dim nWidth As Integer = b2.Width * 3
        ' for some reason although the original code show a formula to come up with the offset this doesn't work very well.
        ' I found that it is just easier to make the offset 0 and so all bits are handled. Basically the problem comes when 
        ' using this on files that don't have
        Dim nOffset As Integer = 0
        Dim nPixel As Integer = 0, npixelmax As Integer = 0
        Dim pos1 As Integer = stride + 3
        Dim pos2 As Integer = stride + 3
        Dim p2minusplus As Integer, p2plusminus As Integer, p2plusplus As Integer, p2minusminus As Integer
        Dim p2minusstride As Integer, p2plusstride As Integer
        Dim p2plus As Integer, p2minus As Integer
 
        For y As Integer = 1 To b.Height - 1
            For x As Integer = 1 To nWidth - 3
 
                p2minusplus = pos2 - stride + 3
                p2plusminus = pos2 + stride - 3
                p2plusplus = pos2 + stride + 3
                p2minusminus = pos2 - stride - 3
                p2minusstride = pos2 - stride
                p2plusstride = pos2 + stride
                p2minus = pos2 - 3
                p2plus = pos2 + 3
                If p2minusplus <= p02.Length - 1 And p2minusplus >= 0 And p2plusminus <= p02.Length - 1 And p2plusminus >= 0 And _
                p2plusplus <= p02.Length - 1 And p2plusplus >= 0 And p2minusminus <= p02.Length - 1 And p2minusminus >= 0 And _
                p2minusstride <= p02.Length - 1 And p2minusstride >= 0 And p2plusstride <= p02.Length - 1 And p2plusstride >= 0 And _
                p2plus <= p02.Length - 1 And p2plus >= 0 And p2minus <= p02.Length - 1 And p2minus >= 0 And pos1 < p01.Length Then
                    npixelmax = Math.Abs(CInt(p02(p2minusplus)) - CInt(p02(p2plusminus)))
                    nPixel = Math.Abs(CInt(p02(p2plusplus)) - CInt(p02(p2minusminus)))
                    If nPixel > npixelmax Then npixelmax = nPixel
                    nPixel = Math.Abs(CInt(p02(p2minusstride)) - CInt(p02(p2plusstride)))
                    If nPixel > npixelmax Then npixelmax = nPixel
                    nPixel = Math.Abs(CInt(p02(p2plus)) - CInt(p02(p2minus)))
                    If nPixel > npixelmax Then npixelmax = nPixel
                    If npixelmax < CInt(threshold) Then npixelmax = 0
                    p01(pos1) = CByte(npixelmax)
                End If
                pos1 += 1
                pos2 += 1
 
            Next
            pos1 += nOffset
            pos2 += nOffset
        Next
 
        System.Runtime.InteropServices.Marshal.Copy(p01, 0, scan01, bytes)
 
        b.UnlockBits(bmData1)
        b2.UnlockBits(bmData2)
 
    End Sub
    Public Sub EdgeDetectHomogenity(ByVal b As Bitmap, ByVal threshold As Byte)
        Dim b2 As Bitmap = b.Clone
        Dim bmData1 As BitmapData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
        Dim bmData2 As BitmapData = b2.LockBits(New Rectangle(0, 0, b2.Width, b2.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
        Dim stride As Integer = bmData2.Stride
        Dim scan01 As IntPtr = bmData1.Scan0
        Dim scan02 As IntPtr = bmData2.Scan0
        Dim bytes As Integer = b.Height * b.Width * 3
        Dim p01(bytes - 1) As Byte
        Dim p02(bytes - 1) As Byte
 
        System.Runtime.InteropServices.Marshal.Copy(scan01, p01, 0, bytes)
        System.Runtime.InteropServices.Marshal.Copy(scan02, p02, 0, bytes)
        Dim nWidth As Integer = b2.Width * 3
        Dim nOffset As Integer = 0
        Dim nPixel As Integer = 0, npixelmax As Integer = 0
        Dim pos1 As Integer = stride + 3
        Dim pos2 As Integer = stride + 3
 
        Dim p2plusminus As Integer, p2plusstride As Integer, p2plusplus As Integer, p2minusstride As Integer, _
        p2minusminus As Integer, p2minusplus As Integer
 
        For y As Integer = 1 To b.Height - 1
            For x As Integer = 1 To nWidth - 3
 
                p2plusminus = pos2 + stride - 3
                p2plusstride = pos2 + stride
                p2plusplus = pos2 + stride + 3
                p2minusstride = pos2 - stride
                p2minusminus = pos2 - stride - 3
                p2minusplus = pos2 - stride + 3
 
                If p2plusminus < p02.Length And p2plusminus >= 0 And p2plusstride < p02.Length And p2plusstride >= 0 And _
                p2plusplus < p02.Length And p2plusplus >= 0 And p2minusstride < p02.Length And p2minusstride >= 0 And _
                p2minusstride < p02.Length And p2minusstride >= 0 And p2minusminus < p02.Length And p2minusminus >= 0 And _
                p2minusplus < p02.Length And p2minusplus >= 0 Then
 
                    npixelmax = Math.Abs(CInt(p02(pos2)) - CInt(p02(p2plusminus)))
                    nPixel = Math.Abs(CInt(p02(pos2)) - CInt(p02(p2plusstride)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
                    nPixel = Math.Abs(CInt(p02(pos2)) - CInt(p02(p2plusplus)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
                    nPixel = Math.Abs(CInt(p02(pos2)) - CInt(p02(p2minusstride)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
                    nPixel = Math.Abs(CInt(p02(pos2)) - CInt(p02(p2plusstride)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
                    nPixel = Math.Abs(CInt(p02(pos2)) - CInt(p02(p2minusminus)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
                    nPixel = Math.Abs(CInt(p02(pos2)) - CInt(p02(p2minusstride)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
                    nPixel = Math.Abs(CInt(p02(pos2)) - CInt(p02(p2minusplus)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
 
                    If npixelmax < threshold Then npixelmax = 0
 
                    p01(pos1) = CByte(npixelmax)
 
                End If
 
                pos1 += 1
                pos2 += 1
            Next
            pos1 += nOffset
            pos2 += nOffset
        Next
 
        System.Runtime.InteropServices.Marshal.Copy(p01, 0, scan01, bytes)
 
        b.UnlockBits(bmData1)
        b2.UnlockBits(bmData2)
 
    End Sub
 
 
    Public Function EdgeEnhance(ByVal b As Bitmap, ByVal threshold As Byte) As Boolean
        Dim b2 As Bitmap = b.Clone
        Dim bmData1 As BitmapData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
        Dim bmData2 As BitmapData = b2.LockBits(New Rectangle(0, 0, b2.Width, b2.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
        Dim stride As Integer = bmData2.Stride
        Dim scan01 As IntPtr = bmData1.Scan0
        Dim scan02 As IntPtr = bmData2.Scan0
        Dim bytes As Integer = b.Height * b.Width * 3
        Dim p01(bytes - 1) As Byte
        Dim p02(bytes - 1) As Byte
 
        System.Runtime.InteropServices.Marshal.Copy(scan01, p01, 0, bytes)
        System.Runtime.InteropServices.Marshal.Copy(scan02, p02, 0, bytes)
        Dim nWidth As Integer = b2.Width * 3
        Dim nOffset As Integer = 0
        Dim nPixel As Integer = 0, npixelmax As Integer = 0
        Dim pos1 As Integer = stride + 3
        Dim pos2 As Integer = stride + 3
        Dim p2minusplus As Integer, p2plusminus As Integer, p2plusplus As Integer, p2minusminus As Integer
        Dim p2minusstride As Integer, p2plusstride As Integer
        Dim p2plus As Integer, p2minus As Integer
 
        For y As Integer = 1 To b.Height - 1
            For x As Integer = 1 To nWidth - 3
 
                p2minusplus = pos2 - stride + 3
                p2plusminus = pos2 + stride - 3
                p2plusplus = pos2 + stride + 3
                p2minusminus = pos2 - stride - 3
                p2minusstride = pos2 - stride
                p2plusstride = pos2 + stride
                p2minus = pos2 - 3
                p2plus = pos2 + 3
                If p2minusplus <= p02.Length - 1 And p2minusplus >= 0 And p2plusminus <= p02.Length - 1 And p2plusminus >= 0 And _
                p2plusplus <= p02.Length - 1 And p2plusplus >= 0 And p2minusminus <= p02.Length - 1 And p2minusminus >= 0 And _
                p2minusstride <= p02.Length - 1 And p2minusstride >= 0 And p2plusstride <= p02.Length - 1 And p2plusstride >= 0 And _
                p2plus <= p02.Length - 1 And p2plus >= 0 And p2minus <= p02.Length - 1 And p2minus >= 0 And pos1 < p01.Length Then
                    npixelmax = Math.Abs(CInt(p02(pos2 - stride + 3)) - CInt(p02(pos2 + stride - 3)))
                    nPixel = Math.Abs(CInt(p02(pos2 + stride + 3)) - CInt(p02(pos2 - stride - 3)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
                    nPixel = Math.Abs(CInt(p02(pos2 - stride)) - CInt(p02(pos2 + stride)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
                    nPixel = Math.Abs(CInt(p02(pos2 + 3)) - CInt(p02(pos2 - 3)))
                    If nPixel > npixelmax Then npixelmax = nPixel
 
                    If npixelmax > threshold And npixelmax > p01(pos1) Then
                        p01(pos1) = CByte(Math.Max(CInt(p01(pos1)), npixelmax))
                    End If
 
                End If
 
                pos1 += 1
                pos2 += 1
            Next
            pos1 += nOffset
            pos2 += nOffset
        Next
 
        System.Runtime.InteropServices.Marshal.Copy(p01, 0, scan01, bytes)
 
        b.UnlockBits(bmData1)
        b2.UnlockBits(bmData2)
 
        Return True
    End Function
 
End Class

 

 

این کد کامل نیست!

دانلود کد فوق از طریق لینک زیر:

CannyInVisualBasic

رمز فایل : behsanandish.com