I'm trying to apply opencv's Threshold
function to a numpy array. I'm using the python bindings for opencv 2.1. It goes like this:
import cv
import numpy as np
a = np.random.rand(1024,768)
cv.Threshold(a,a,0.5,1,cv.CV_THRESH_BINARY)
and this throws an error:
OpenCV Error: Unsupported format or combination of formats () in threshold
So, I'm not convinced I know what I'm doing, but I was hoping Threshold
would work like, for example, Smooth
, wherein I can run
cv.Smooth(a,a)
with no problems, and end up with a smooth(er) image. I'm not sure how to think about "formats" of numpy arrays as opencv sees them, but I'm loathe to convert the numpy array into an opencv image format if I don't have to (and all my attempts have failed so far anyway).
I'd like to know why Threshold
is not working in the obviously naive way I'm trying to make it work, and it would be great to know what I should be doing instead.
P.S. I know I could perform a thresholding operation on the numpy array myself, but I'm trying to figure out opencv.
Apparently the Threshold
method is more fussy than Smooth - it only works on 8 bit integer / 32 bit floating point arrays (see here) so your code snippet above won’t work because numpy arrays default to float64.
So if you change the line where you create the array to force the precision to 32 bit float
>>> a = np.array(np.random.rand(1024,768),dtype=‘float32’)
then it’s happy to threshold:
>>> ((a>0) & (a<1)).sum()
786432
>>> cv.Threshold(a,a,0.5,1,cv.CV_THRESH_BINARY)
>>> ((a>0) & (a<1)).sum()
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With