Search code examples
pythonopencvsift

can't use SIFT on a numpy array image


I open a Brain MRI scan:

path = os.path.join(r"C:\temp\generated_noisy\patients", 
lst_of_filenames[index_of_filename])
scan = nib.load(path)
data = scan.get_data()
data = data[14:168,18:205,98]

so now "data" is a numpy array (the elemnts in it are "numpy.float64"):

print(pic.shape)
print(type(pic))
print(type(pic[50,50]))

(154, 187)
<class 'numpy.ndarray'>
<class 'numpy.float64'>

Allright, now I try to use SIFT: kp,des = sift.detectAndCompute(pic,None)

and I get this error:

OpenCV(3.4.2) C:\projects\opencv- 
python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1121: error: (-5:Bad 
argument) image is empty or has incorrect depth (!=CV_8U) in function 
'cv::xfeatures2d::SIFT_Impl::detectAndCompute'

Anyone know how to solve this? I can't seem to find any help online...


Solution

  • SIFT expects the data type to be uint8. However, you won't be able to just convert the array to uint8 if the values are not in the correct range, such as being greater than 255 or in the range 0-1. Before converting, you could scale the values so the values are in the range 0-255. For example, the following will subtract the minimum value so the minimum is zero, then scale so the max is 255. Then you can convert to type uint8 without corrupting the image.

    data = (data - np.min(data)) * 255 / np.max(data)
    data = data.astype(np.uint8)