Resolves the implementation of box filter in OpenCV and proposes a further accelerated scheme (source sharing).

Source: Internet
Author: User

Description: All the algorithms involved in the optimization are referred to on the PC, for other architectures are appropriate unknown, please self-test.

Box Filter, the most classic of a field operation, in countless occasions have a wide range of applications, as a very basic function, its performance directly affects the performance of other related functions, the most typical is now a good EPF filter: Guidefilter. So the level and degree of optimization is very important, the network has a lot of relevant code and blog on the algorithm to explain and optimize, put forward a lot of O (1) algorithm, but the so-called 0 (1) algorithm has advantages and disadvantages, 0 (1) only indicates that the execution time and a parameter independent, but its own time-consuming or different. The more popular is the cumulative histogram method, in fact, this is very undesirable, because a slightly larger picture will lead to overflow, here we parse the OPENCV of the relevant code, see how he is optimized.

First find the location of the OPENCV code, which is in \opencv\sources\modules\imgproc\src\smooth.cpp.

Box filter is a column can be separated from the filter, so the OPENCV is also processed, the line direction of the filter, to get the intermediate results, and then the intermediate results in the direction of the processing, the final result is obtained.

The relevant code for OPENCV line Direction processing is as follows:

Template<typename T, TypeName st>struct rowsum:        public baserowfilter{    rowsum (int _ksize, int _anchor):        baserowfilter ()    {        ksize = _ksize;        Anchor = _anchor;    }    virtual void operator () (const uchar* SRC, uchar* dst, int width, int cn) {Const t* S = (const t*) src; st* D = (st*) dst; int i = 0, k, ksz_cn = Ksize*cn; width = (width-1) *cn; for (k = 0; K < cn; k++, s++, d++ ) {ST s = 0; for (i = 0; i < ksz_cn; i + = cn) S + = s[i]; D[0] = s; for (i = 0; i < width; i + = cn) {s + = S[i + ksz_cn]- s[i]; D[I+CN] = s;}} }};

This code takes into account multiple channels and multiple data types, in order to analyze the core code that allows us to rewrite the next single channel.

for (Z = 0, Value = 0; Z < Size; z++)        Value + = Rowdata[z]; Linepd[0] = value;for (X = 1; X < Width; X + +) {    Value + = rowdata[x + Size-1]-rowdata[x-1];        LINEPD[X] = Value;               }    

In the code above, RowData is the pixel value expanded for a row of pixels, Width + radius + radius, radius is the radius of the value filter, and the code size = 2 * radius + 1,LINEPD is the so-called intermediate result, considering the data type can The scope of the expression must use the Int type.

For the first point in each row, it is simple to calculate the accumulated value within the specified radius of the travel direction directly with for. And then all points, with the previous cumulative value plus the newly added points, and then to remove the point of emigration, to obtain a new cumulative value. This method is mentioned in many literatures, and there is nothing new, and there is not much to say here.

According to normal thinking, the processing in the column direction should be exactly the same as the direction of the row, only the direction of processing, the different data sources and the final need for the results of a normalization process. This is true, there are many algorithms are doing this, but due to some of the CPU architecture (mainly the increase of the cache miss), the same algorithm along the column direction will always be more than the line in the direction of a grade, there are many ways to solve, such as the first transpose the intermediate results, It is then processed in accordance with the rules of the line direction, after which the data is transferred back. The transpose process is highly efficient, with the help of SSE and cache optimization, which can achieve 4 times times faster than the original dual for loop. There is another way, as shown in the column processing in OpenCV, which is highlighted below.

In the OPENCV code, not directly in the direction of the column, but to continue along the line in the direction of a row of processing, I first posted my own translation of the Pure C code to explain:

    for (Y = 0; Y < Size-1; y++)            //    Note there is no last item Oh                          {        int *lineps = (int *) (sum->data + colpos[y] * sum->widthstep); C8/>for (X = 0; X < Width; x + +)    colsum[x] + = lineps[x];    }    for (Y = 0; Y < Height; y++)    {        unsigned char* linepd    = dest->data + Y * dest->widthstep;            int *addpos              = (int*) (Sum->data + colpos[y + Size-1] * sum->widthstep); int *subpos = (int*) (sum->data + colpos[y] * sum->widthstep); for (X = 0; X < Width; x + +) {Value = colsum[x] + addpos[x]; LINEPD[X] = Value * scale; COLSUM[X] = Value- subpos[x];}}         

The code above defines a colsum to hold the accumulated values for each of the intermediate elements within a specified radius in the column direction for each row, for the first row, for special handling, and for each element of the other rows to be treated in the same way as in the Baserowfilter, but only in writing. Special attention is to the first row of the accumulation, the last element is not counted, this processing technique in the following X-cycle is reflected, please carefully appreciate.

The advantage of the above code is that it can effectively reduce the cache miss of the CPU, but the total computational amount is not changed, so it can effectively improve the speed.

For the PC, in the OPENCV, it uses SSE for further optimization in the column direction, and we post the code that handles the Uchar type:

View Code

The code is more, I'm a little leaner (note that the streamlined is not operational, but more clearly expressed the idea).

virtual void operator () (const uchar** SRC, uchar* dst, int dststep, int count, intwidth) {intI int*SUM; BOOL Havescale = scale! = 1; Double _scale =Scale if (Width! = (int) Sum.size ()) {sum.resize (width); sumcount = 0; } SUM = &sum[0]; if (Sumcount = = 0) {memset ((void*) SUM, 0, width*sizeof (int)); for (; Sumcount < ksize-1; sumcount++, src++) {Const int* Sp = (const int*) src[0]; i = 0; for (; I <= width-4; i+=4) {__m128i _sum = _mm_loadu_si128 ((const __m128i*) (sum+i)); __m128i _sp = _mm_loadu_si128 ((const __m128i*) (sp+i)); _mm_storeu_si128 ((__m128i*) (sum+i), _mm_add_epi32 (_sum, _sp)); } for (; i < width; i++) Sum[i] + =Sp[i]; }} else{src + = ksize-1; } for (; count--; src++) {Const int* Sp = (const int*) src[0]; Const int* SM = (const int*) src[1-Ksize]; uchar* D = (uchar*) DST; i = 0; Const __m128 SCALE4 = _mm_set1_ps ((float) _scale); for (; I <= width-8; i+=8) {__m128i _sm = _mm_loadu_si128 ((const __m128i*) (sm+i)); __m128i _sm1 = _mm_loadu_si128 ((const __m128i*) (sm+i+4)); __m128i _s0 = _mm_add_epi32 (_mm_loadu_si128 ((const __m128i*) (sum+  i)), _mm_loadu_si128 ((const __m128i*) (sp+  i)); __m128i _s01 = _mm_add_epi32 (_mm_loadu_si128 ((const __m128i*) (Sum+i+4 )), _mm_loadu_si128 ((const __m128i*) (Sp+i +4 ))); __m128i _s0t =  _mm_cvtps_epi32 (_mm_mul_ps (Scale4, _mm_cvtepi32_ps (_S0))), __m128i _s0t1 =  _mm_cvtps_epi32 ( _mm_mul_ps (Scale4, _mm_cvtepi32_ps (_S01))); _s0t =  _mm_packs_epi32 (_s0t, _s0t1), _mm_storel_epi64 ((__m128i*) (d+  i), _mm_packus_epi16 (_s0t, _s0t)); _mm _storeu_si128 ((__m128i*) (sum+  i), _mm_sub_epi32 (_S0,_SM)), _mm_storeu_si128 ((__m128i*) (Sum+i+4 ), _mm_ SUB_EPI32 (_S01,_SM1)); } for (; i < width; i++ ) {int s0 = Sum[i] +  sp[i]; D[i] = saturate_cast<uchar> (s0*  _scale); Sum[i] = S0- sm[i];} DST + =  dststep;}}          

In the line direction, colsum each element of the update is not related to each other, so, with the help of SSE can achieve a one-time update of four elements, and the above code will also be the first line of the special calculation is also used SSE implementation, although this part of the calculation is very small.

In the specific SSE details, for the Uchar type, although the intermediate result is expressed in int type, the SSE does not have a division instruction for shaping (is there?). ), therefore, the above borrowed a floating-point multiplication SSE instruction implementation, of course, more _mm_cvtepi32_ps and _mm_cvtps_epi32 such a function of the type conversion. If there is a plastic division, that would be better.

SSE implementation, is simply to use _mm_loadu_si128 loading data, with _MM_ADD_EPI32, _MM_MUL_PS and other functions for basic operations, with the _mm_storeu_si128 to save data, and there is no particularly complicated parts, Note that considering the universality of the data, it is not necessarily 16-byte aligned, so in the loading and saving is the need to use the U aspect of the function, in fact, now the _mm_loadu_si128 and _mm_load_si128 in the processing speed has no particularly obvious difference.

Note that after each SSE code, there is always some C code, this is because our actual data width is not necessarily 4 of the integer times, the part that is not processed by SSE must use C implementation, which is actually very good for the reader, because we can understand this part of the C Code of the SSE code is what to do.

The above is the OpenCV box filter implementation of the key code, if the reader to see the details, OpenCV also for the mobile phone neon optimization, in fact, this and SSE is basically the same meaning.

Whether there is room for improvement, from my cognition, in the vertical direction of the treatment, should not have, but the horizontal direction, SSE has no place, after my thinking I think there is.

In the calculation of the row direction, the For loop is the primary calculation.

for (X = 1; X < Width; X + +) {    Value + = rowdata[x + Size-1]-rowdata[x-1];        LINEPD[X] = Value;               }  

I think that although the operation here is dependent, the global cannot be parallelized, but observe this line of code:

Value + = rowdata[x + Size-1]-rowdata[x-1];    

of which Rowdata[x + Size-1]-rowdata[x-1]; is not dependent on, can be parallel, so if all the difference is calculated quickly in advance, then the space to speed up is still relatively large, that is, the need to calculate the following function in advance:

for (X = 0; X < (WIDTH-1); x + +)     diff[x] = addpos[x]-subpos[x];

The implementation of SSE here is very simple:

 unsigned char *addpos = rowdata + Size *  Channel;        unsigned char *subpos =  rowdata;                    X = 0;        Note that this assignment is outside of the loop below, which avoids the width<8 when the second for Loop loop variable is uninitialized __m128i Zero =  _mm_setzero_si128 (); for (; X <= (Width-1) * CHANNEL-8; X + = 8 ) {__m128i Add = _mm_unpacklo_epi8 (_mm_loadl_epi64 (__m128i const *) (Addpos +  X), Ze                    RO); __m128i Sub = _mm_unpacklo_epi8 (_mm_loadl_epi64 (__m128i const *) (Subpos +  X)), Zero); _mm_store_si128 ((__m128i *) (Diff + X + 0), _mm_sub_epi32 (_mm_unpacklo_epi16 (ADD, Zero), _mm_unpacklo_epi16 (Sub, zero)); Because the _aligned_malloc function is used to allocate memory, the _mm_store_si128 _mm_store_si128 ((__m128i *) (Diff + X + 4 ), _MM_SUB_EPI32 (_mm_ Unpackhi_epi16 (Add, Zero), _mm_unpackhi_epi16 (Sub, Zero)); } for (; X < (Width-1) * Channel; x + + ) diff[x] = addpos[x]-subpos[x];         

and the column direction of SSE processing code is different, here is loaded UCHAR data, so loaded function is different, the way of processing also has a difference, the above several SSE functions to check MSDN can understand its meaning, or very tasty.

After this treatment, the test found that the speed can be 30% higher than the OPENCV version, is also an additional surprise.

Further optimizations may be limited in speed, such as dividing the rest of the for loop internally into four paths and so on.

In my I5 desktop, using the above algorithm to 1024*1024 three-channel color image of a radius of 5 test, 100 times the calculation of the pure algorithm part of the time is 800ms, if the pure C version is about 1800ms, when the radius is 200, the SSE version is about 950MS, C version of about 1900ms, when the radius is 400, SSE version is about 1000ms, C version about 2100ms; visible, radius increases, time-consuming slightly increased, mainly because the algorithm has some initialization of the calculation and radius related, but these are not important.

In the case of not using multithreading (although this algorithm is very suitable for multithreaded computing), without using the GPU, only using single-threaded \CPU for calculation, personally feel that the current code is very difficult for me to go beyond the quality , in some ways, The time spent in the code for calculations may be shorter than the time it takes to wait for data from memory, and there seems to be no better algorithm to further reduce the amount of memory data accessed.

I am here to invite you master to the current optimization of this code for further optimization, I hope the man not humble.

Source code (VS2010 written): Box Filter

Operating interface:

  

The code of this article is for the commonly used image data optimization processing, in many cases, the need to deal with int or float type, such as Guidefilter, if the reader understand the principles of the Code interpreted in this article, change the code to adapt to them is a very simple thing, if you do not, So also please do not give me a message, or I can offer, because in essence I like to provide fishing, rather than fish, fishing gear has been sent to you, you are looking for me to fish, it can only ...

LAVIEWPBT Time: 2015.12.17 contact qq:33184777 Reprint Please keep our information **********************

Resolves the implementation of box filter in OpenCV and proposes a further accelerated scheme (source sharing).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.