I tried to cv::bitwise_not to a cv::Mat matrix of double values. I applied like
cv::bitwise_not(img, imgtemp);
img is CV_64F data of 0 and 1. But imgtemp has all nonsense data inside.
I am expecting 0 in img to be 1 at imgtemp and 1 in img to be 0 at imgtemp. How to apply bitwise_not to a double Mat matrix?
Thanks
I cannot get the sense of doing a bitwise not of a double (floating point) value: you will be doing bitwise operations also on the exponent (see here). All bits will be inverted, from 0 to 1 and viceversa.
There is also a note on this aspect in the function documentation.
In case of a floating-point input array, its machine-specific bit
representation (usually IEEE754-compliant) is used for the operation.
If you want zeros to become ones and viceversa, as you suggested, you could do:
cv::threshold(warpmask, warpmaskTemp,0.5,1.0,THRESH_BINARY_INV)
(see documentation) (and yes, you can use same matrix for input and destination).
I think you are either getting the method signature wrong or wrongly named the parameters for the bitwise_not method.
According to [OpenCV 2.4.6 Documentation on bitwise_not() method] (http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#void bitwise_not(InputArray src, OutputArray dst, InputArray mask))
void bitwise_not(InputArray src, OutputArray dst, InputArray mask=noArray())
If you are going to use any mask, it needs to be the last argument as mask is an optional for 'bitwise_not' method.
Additionally, all the data types need to be the same in order to avoid confusion. What I am trying to imply is that your source and destination data formats and any interim ones such as the method parameters must be in the same format. You cannot have on ein CV_64F and others in different. If I am not loosing my marbles here, bitwise operation would possibly require you to have all the data in unsigned or signed integer format for the sake of simplicity. Nevertheless, you should have all the types same.
About the garbage that you got, I think it is a general and good programming practice that you initialise your variables with some reasonable values. This helps when you are debugging step by step and ascertain the details where it failed.
Give it a try.
To follow on from Antonio's answer, you should use the right tool for the job. double is not an appropriate storage medium for boolean data.
In open cv you can type a boolean as an unsigned char (8bits). Although in typing your own true value you can pick any non-zero value, in open cv it is more natural to have 0/255; that way fitting in with open cv's bitwise operations and comparison operators. E.g. a bitwise not could be achieved by result = (input == 0) which can take any type. threshold in Antonio's answer maintains the same type (useful in some circumstances). For bitwise_not you should have it in the boolean format first.
Unfortunately opencv makes it very difficult to work with black and white bitwise data.
Related
I frequently encounter that issue but I don't really know a proper way to fix it.
I just would like some advise to do it the regarding to the processing time.
I am using opencv and I want to realize that operation:
map |= mask & mu(0);
map is a matrix of single precision float.
mask is a matrix of unsigned char that only contain 0 for the statement false ot 255 (0xFF) for the statement true
mu is a double precision float scalar value.
Usually I do realize that operation that way :
cv::multiply(mask,mu(0),mask, 1./255., CV_32F);
map |= mask
Regarding also to the transparent vectorize classes (header openc2/core/hal/intrinsics.hpp) is there a more efficient way to do such operation ?
Thank you in advance for any help.
As highlighted by api55 could be fix by using directly the bitwise function rather than using the operator overload.
Thank you api55
I used metal to do some interpolation task. I wrote the kernel function as followed:
kernel void kf_interpolation( device short *dst, device uchar *src, uint id [[ thread_position_in_grid ]] )
{
dst[id] = src[id-1] + src[id] + src[id+1];
}
That kernel function could not gave expected value. And I found the cause was that the src[id-1] was always 0, which was false value. However, src[id+1] contained the right value. The question is how could I use the neighbour unit correctly, e.g. [id-1], in kernel functions. Thanks in advance.
The most efficient way to handle edge cases like this is usually to grow your source array at each end and offset the indices. So for N calculations, allocate your src array with N+2 elements, fill elements 1 through N (inclusive) with the source data, and set element 0 and N+1 to whatever you want the edge condition to be.
An even more efficient method would be to use MTLTextures instead of MTLBuffers. MTLTextures have an addressing mode attached to them which causes the hardware to automatically substitute either zero or the nearest valid texel when you read off the edge of a texture. They can also do linear interpolation in hardware for free, which can be of great help for resampling, assuming bilinear interpolation is good enough for you. If not, I recommend looking at MPSImageLanczosScale as an alternative.
You can make a MTLTexture from a MTLBuffer. The two will alias the same pixel data.
In Matlab, I can use logical(img) to convert all non-zero element to one.
Is there a simple way(i.e. without loop) to convert all non-zero stored in cv::Mat to one in OpenCV?
Thanks!
There number of functions that may help you but that depends on what you have and what you are trying to get.
1) OpenCV has function compare and operator '!=' (as well as any other operator you may need). You can write:
img = (img != 0);
This will convert any non-zero value of matrix to 255. I know that you wanted to convert it to 1, but if 255 is good enough for you than this is the best method. In any task I encountered in the past conversion to 255 was always better than conversion to 1, because you can use resulting image for all kinds of bitwise operations like logic AND, OR, etc...
2) If you do want to make conversion to 1, and your matrix is positive integers (or chars, or shorts), you can use function min.
img = min(img,1);
3) Also you can use function threshold as #Roger Rowland suggested.
You could use the threshold() function in OpenCV for convenience.
You mention "non-zero" elements. If your matrix has negative numbers, and you still want those to be set to 1, use threshold( abs(my_mat), .. ).
In general, this can also be done through this:
Mat my_mat;
Mat reference = Mat::zeros( rows, cols, type );
Mat result = (abs(my_mat) > reference)/255;
This is longer, and probably looks messier, but it has the advantage that reference can be adjusted to something other than all zeros if required (it could be a gradient, for example). Also, < is not the only operator that can fit there- any logical operator can be used. The result of a logical operation is always either 0 or 255, hence the division.
My current problem is that I would like to know the type of the cv::Mat-frames grabbed by cv::VideoCapture from a video file. The documentation doesn't specify that (as is often the case, so even if I have overlooked it in this particular case, it would still be helpful to get an answer for dealing with the problem in general).
Of course, I could open the appropriate OpenCV header file and go through the CV_64FC2, ... macros to find a macro which matches the Mat's type(). But I'm kind of sick of that. There must be an easier way.
Isn't there any function that lets me translate a Mat's type() to a human-readable format ? Like this:
cv::Mat myMatWithUnknownType;
// Some code modifying myMatWithUnknownType.
// ...
std::string readableType = myMatWithUnknownType.typeString();
std::cout << readableType; // Prints "CV_64FC3".
How do you deal with that?
First, the format that come from cameras is only one: CV_8UC3. This is hardcoded in OpenCV, and any video format is converted to this before being sent to user. So
capture >> frame;
Will always return a RGB image, of 8 bits per channel.
Now, for other types you can write your function, keeping in mid that there are not so many types supported in OpenCV: A Mat can be of type char, uchar, short, ushort, int, uint, float, double, of 1 to 512 channels (according to the latest docs.) So writing your own type_to_string() is not difficult.
I've read that the signed char and unsigned char types are not guaranteed to be 8 bits on every platform, but sometimes they have more than 8 bits.
If so, using OpenCv how can we be sure that CV_8U is always 8bit?
I've written a short function which takes a 8 bit Mat and happens to convert, if needed, CV_8SC1 Mat elements into uchars and CV_8UC1 into schar.
Now I'm afraid it is not platform independent an I should fix the code in some way (but don't know how).
P.S.: Similarly, how can CV_32S always be int, also on machine with no 32bit ints?
Can you give a reference of this (I've never heard of that)? Probably you mean the padding that may be added at the end of a row in a cv::Mat. That is of no problem, since the padding is usually not used, and especially no problem if you use the interface functions, e.g. the iterators (c.f.). If you would post some code, we could see, if your implementation actually had such problems.
// template methods for iteration over matrix elements.
// the iterators take care of skipping gaps in the end of rows (if any)
template<typename _Tp> MatIterator_<_Tp> begin();
template<typename _Tp> MatIterator_<_Tp> end();
the CV_32S will be always 32-bit integer because they use types like those defined in inttypes.h (e.g. int32_t, uint32_t) and not the platform specific int, long, whatever.