I'm trying to fill zero regions in a matrix using memset() in this way:
unsigned short *ptr;
for(int i=0; i < nRows; ++i)
{
ptr = DepthMat.ptr<unsigned short>(i); /* OCV matrix of uint16 values */
for(int j=0; j<nCols; ++j)
{
uint n=0;
if(ptr[j] == 0) /* zero region found */
{
d_val = ptr[j-1]; /* saves last non-zero value */
while(ptr[j+n] == 0)
{ /* looks for non zero */
++n;
}
d_val = (d_val < ptr[j+n] ? d_val : ptr[j+n]);
memset( ptr+j, d_val, n*sizeof( ptr[0]) );
j += n;
}
}
}
I look for sequences of zero, then I store the positions (ptr+j-1
and ptr+j+n
) and the values of the zero regions boundaries, and finally I use memset() to replace the zeros with d_val.
The problem is that when I check the values stored they don't match with d_val, for example, I put the value '222' but I get '57054'.
Any clue?
The value argument to memset()
is only a single byte, even though the type for the argument is int
.
The manual page describes the function as:
memset - fill memory with a constant byte
So, no more than the least-significant 8 bits of d_val
will be written to memory. Since you're treating the memory as an array of short
, you get "mangled" values that consist of the same byte repeated through the bytes of the short
.
In ... short, don't do this; use a for
loop to do a repeated write of actual short
s.