ocl: change processing of OpenCL failures
[profile/ivi/opencv.git] / modules / cudaimgproc / src / hough_circles.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
23 //   * Redistribution's in binary form must reproduce the above copyright notice,
24 //     this list of conditions and the following disclaimer in the documentation
25 //     and/or other materials provided with the distribution.
26 //
27 //   * The name of the copyright holders may not be used to endorse or promote products
28 //     derived from this software without specific prior written permission.
29 //
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
40 //
41 //M*/
42
43 #include "precomp.hpp"
44
45 using namespace cv;
46 using namespace cv::cuda;
47
48 #if !defined (HAVE_CUDA) || defined (CUDA_DISABLER) || !defined(HAVE_OPENCV_CUDAFILTERS)
49
50 Ptr<cuda::HoughCirclesDetector> cv::cuda::createHoughCirclesDetector(float, float, int, int, int, int, int) { throw_no_cuda(); return Ptr<HoughCirclesDetector>(); }
51
52 #else /* !defined (HAVE_CUDA) */
53
54 namespace cv { namespace cuda { namespace device
55 {
56     namespace hough
57     {
58         int buildPointList_gpu(PtrStepSzb src, unsigned int* list);
59     }
60
61     namespace hough_circles
62     {
63         void circlesAccumCenters_gpu(const unsigned int* list, int count, PtrStepi dx, PtrStepi dy, PtrStepSzi accum, int minRadius, int maxRadius, float idp);
64         int buildCentersList_gpu(PtrStepSzi accum, unsigned int* centers, int threshold);
65         int circlesAccumRadius_gpu(const unsigned int* centers, int centersCount, const unsigned int* list, int count,
66                                    float3* circles, int maxCircles, float dp, int minRadius, int maxRadius, int threshold, bool has20);
67     }
68 }}}
69
70 namespace
71 {
72     class HoughCirclesDetectorImpl : public HoughCirclesDetector
73     {
74     public:
75         HoughCirclesDetectorImpl(float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles);
76
77         void detect(InputArray src, OutputArray circles);
78
79         void setDp(float dp) { dp_ = dp; }
80         float getDp() const { return dp_; }
81
82         void setMinDist(float minDist) { minDist_ = minDist; }
83         float getMinDist() const { return minDist_; }
84
85         void setCannyThreshold(int cannyThreshold) { cannyThreshold_ = cannyThreshold; }
86         int getCannyThreshold() const { return cannyThreshold_; }
87
88         void setVotesThreshold(int votesThreshold) { votesThreshold_ = votesThreshold; }
89         int getVotesThreshold() const { return votesThreshold_; }
90
91         void setMinRadius(int minRadius) { minRadius_ = minRadius; }
92         int getMinRadius() const { return minRadius_; }
93
94         void setMaxRadius(int maxRadius) { maxRadius_ = maxRadius; }
95         int getMaxRadius() const { return maxRadius_; }
96
97         void setMaxCircles(int maxCircles) { maxCircles_ = maxCircles; }
98         int getMaxCircles() const { return maxCircles_; }
99
100         void write(FileStorage& fs) const
101         {
102             fs << "name" << "HoughCirclesDetector_CUDA"
103             << "dp" << dp_
104             << "minDist" << minDist_
105             << "cannyThreshold" << cannyThreshold_
106             << "votesThreshold" << votesThreshold_
107             << "minRadius" << minRadius_
108             << "maxRadius" << maxRadius_
109             << "maxCircles" << maxCircles_;
110         }
111
112         void read(const FileNode& fn)
113         {
114             CV_Assert( String(fn["name"]) == "HoughCirclesDetector_CUDA" );
115             dp_ = (float)fn["dp"];
116             minDist_ = (float)fn["minDist"];
117             cannyThreshold_ = (int)fn["cannyThreshold"];
118             votesThreshold_ = (int)fn["votesThreshold"];
119             minRadius_ = (int)fn["minRadius"];
120             maxRadius_ = (int)fn["maxRadius"];
121             maxCircles_ = (int)fn["maxCircles"];
122         }
123
124     private:
125         float dp_;
126         float minDist_;
127         int cannyThreshold_;
128         int votesThreshold_;
129         int minRadius_;
130         int maxRadius_;
131         int maxCircles_;
132
133         GpuMat dx_, dy_;
134         GpuMat edges_;
135         GpuMat accum_;
136         Mat tt; //CPU copy of accum_
137         GpuMat list_;
138         GpuMat result_;
139         Ptr<cuda::Filter> filterDx_;
140         Ptr<cuda::Filter> filterDy_;
141         Ptr<cuda::CannyEdgeDetector> canny_;
142     };
143
144     bool centersCompare(Vec3f a, Vec3f b) {return (a[2] > b[2]);}
145
146     HoughCirclesDetectorImpl::HoughCirclesDetectorImpl(float dp, float minDist, int cannyThreshold, int votesThreshold,
147                                                        int minRadius, int maxRadius, int maxCircles) :
148         dp_(dp), minDist_(minDist), cannyThreshold_(cannyThreshold), votesThreshold_(votesThreshold),
149         minRadius_(minRadius), maxRadius_(maxRadius), maxCircles_(maxCircles)
150     {
151         canny_ = cuda::createCannyEdgeDetector(std::max(cannyThreshold_ / 2, 1), cannyThreshold_);
152
153         filterDx_ = cuda::createSobelFilter(CV_8UC1, CV_32S, 1, 0);
154         filterDy_ = cuda::createSobelFilter(CV_8UC1, CV_32S, 0, 1);
155     }
156
157     void HoughCirclesDetectorImpl::detect(InputArray _src, OutputArray circles)
158     {
159         using namespace cv::cuda::device::hough;
160         using namespace cv::cuda::device::hough_circles;
161
162         GpuMat src = _src.getGpuMat();
163
164         CV_Assert( src.type() == CV_8UC1 );
165         CV_Assert( src.cols < std::numeric_limits<unsigned short>::max() );
166         CV_Assert( src.rows < std::numeric_limits<unsigned short>::max() );
167         CV_Assert( dp_ > 0 );
168         CV_Assert( minRadius_ > 0 && maxRadius_ > minRadius_ );
169         CV_Assert( cannyThreshold_ > 0 );
170         CV_Assert( votesThreshold_ > 0 );
171         CV_Assert( maxCircles_ > 0 );
172
173         const float idp = 1.0f / dp_;
174
175         filterDx_->apply(src, dx_);
176         filterDy_->apply(src, dy_);
177
178         canny_->setLowThreshold(std::max(cannyThreshold_ / 2, 1));
179         canny_->setHighThreshold(cannyThreshold_);
180
181         canny_->detect(dx_, dy_, edges_);
182
183         ensureSizeIsEnough(2, src.size().area(), CV_32SC1, list_);
184         unsigned int* srcPoints = list_.ptr<unsigned int>(0);
185         unsigned int* centers = list_.ptr<unsigned int>(1);
186
187         const int pointsCount = buildPointList_gpu(edges_, srcPoints);
188         if (pointsCount == 0)
189         {
190             circles.release();
191             return;
192         }
193
194         ensureSizeIsEnough(cvCeil(src.rows * idp) + 2, cvCeil(src.cols * idp) + 2, CV_32SC1, accum_);
195         accum_.setTo(Scalar::all(0));
196
197         circlesAccumCenters_gpu(srcPoints, pointsCount, dx_, dy_, accum_, minRadius_, maxRadius_, idp);
198
199         accum_.download(tt);
200
201         int centersCount = buildCentersList_gpu(accum_, centers, votesThreshold_);
202         if (centersCount == 0)
203         {
204             circles.release();
205             return;
206         }
207
208         if (minDist_ > 1)
209         {
210             AutoBuffer<ushort2> oldBuf_(centersCount);
211             AutoBuffer<ushort2> newBuf_(centersCount);
212             int newCount = 0;
213
214             ushort2* oldBuf = oldBuf_;
215             ushort2* newBuf = newBuf_;
216
217             cudaSafeCall( cudaMemcpy(oldBuf, centers, centersCount * sizeof(ushort2), cudaMemcpyDeviceToHost) );
218
219             const int cellSize = cvRound(minDist_);
220             const int gridWidth = (src.cols + cellSize - 1) / cellSize;
221             const int gridHeight = (src.rows + cellSize - 1) / cellSize;
222
223             std::vector< std::vector<ushort2> > grid(gridWidth * gridHeight);
224
225             const float minDist2 = minDist_ * minDist_;
226
227             std::vector<Vec3f> sortBuf;
228             for(int i=0; i<centersCount; i++){
229                 Vec3f temp;
230                 temp[0] = oldBuf[i].x;
231                 temp[1] = oldBuf[i].y;
232                 temp[2] = tt.at<int>(temp[1]+1, temp[0]+1);
233                 sortBuf.push_back(temp);
234             }
235             std::sort(sortBuf.begin(), sortBuf.end(), centersCompare);
236
237             for (int i = 0; i < centersCount; ++i)
238             {
239                 ushort2 p;
240                 p.x = sortBuf[i][0];
241                 p.y = sortBuf[i][1];
242
243                 bool good = true;
244
245                 int xCell = static_cast<int>(p.x / cellSize);
246                 int yCell = static_cast<int>(p.y / cellSize);
247
248                 int x1 = xCell - 1;
249                 int y1 = yCell - 1;
250                 int x2 = xCell + 1;
251                 int y2 = yCell + 1;
252
253                 // boundary check
254                 x1 = std::max(0, x1);
255                 y1 = std::max(0, y1);
256                 x2 = std::min(gridWidth - 1, x2);
257                 y2 = std::min(gridHeight - 1, y2);
258
259                 for (int yy = y1; yy <= y2; ++yy)
260                 {
261                     for (int xx = x1; xx <= x2; ++xx)
262                     {
263                         std::vector<ushort2>& m = grid[yy * gridWidth + xx];
264
265                         for(size_t j = 0; j < m.size(); ++j)
266                         {
267                             float dx = (float)(p.x - m[j].x);
268                             float dy = (float)(p.y - m[j].y);
269
270                             if (dx * dx + dy * dy < minDist2)
271                             {
272                                 good = false;
273                                 goto break_out;
274                             }
275                         }
276                     }
277                 }
278
279                 break_out:
280
281                 if(good)
282                 {
283                     grid[yCell * gridWidth + xCell].push_back(p);
284
285                     newBuf[newCount++] = p;
286                 }
287             }
288
289             cudaSafeCall( cudaMemcpy(centers, newBuf, newCount * sizeof(unsigned int), cudaMemcpyHostToDevice) );
290             centersCount = newCount;
291         }
292
293         ensureSizeIsEnough(1, maxCircles_, CV_32FC3, result_);
294
295         int circlesCount = circlesAccumRadius_gpu(centers, centersCount, srcPoints, pointsCount, result_.ptr<float3>(), maxCircles_,
296                                                   dp_, minRadius_, maxRadius_, votesThreshold_, deviceSupports(FEATURE_SET_COMPUTE_20));
297
298         if (circlesCount == 0)
299         {
300             circles.release();
301             return;
302         }
303
304         result_.cols = circlesCount;
305         result_.copyTo(circles);
306     }
307 }
308
309 Ptr<HoughCirclesDetector> cv::cuda::createHoughCirclesDetector(float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles)
310 {
311     return makePtr<HoughCirclesDetectorImpl>(dp, minDist, cannyThreshold, votesThreshold, minRadius, maxRadius, maxCircles);
312 }
313
314 #endif /* !defined (HAVE_CUDA) */