Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Depth error in 2D image with OpenCV Python

Tags:

python

opencv

I am trying to compute the Canny Edges in an image (ndarray) using OpenCV with Python.

slice1 = slices[15,:,:]
slice1 = slice1[40:80,60:100]
print slice1.shape
print slice1.dtype
slicecanny = cv2.Canny(slice1, 1, 100)

Output:

(40, 40)
float64
...
error: /Users/jmerkow/code/opencv-2.4.6.1/modules/imgproc/src/canny.cpp:49: 
error: (-215) src.depth() == CV_8U in function Canny

For some reason I get the above error. Any ideas why?

like image 697
jmerkow Avatar asked Sep 30 '13 21:09

jmerkow


3 Answers

Slice1 will need to be casted or created as a uint8. CV_8U is just an alias for the datatype uint8.

import numpy as np slice1Copy = np.uint8(slice1) slicecanny = cv2.Canny(slice1Copy,1,100) 
like image 169
Ross Avatar answered Oct 19 '22 03:10

Ross


In order to avoid losing precision while changing the data type to uint8, you can first adapt the scale to the 255 format just doing:

(image*255).astype(np.uint8)

Here I'm considering that image is a numpy array and np stand for numpy. I hope it can help someone!

like image 21
Toda Avatar answered Oct 19 '22 02:10

Toda


You can work around this error by saving slice1 to a file and then reading it

from scipy import ndimage, misc
misc.imsave('fileName.jpg', slice1)
image = ndimage.imread('fileName.jpg',0)
slicecanny = cv2.Canny(image,1,100)

This is not the most elegant solution, but it solved the problem for me

like image 21
rifkinni Avatar answered Oct 19 '22 01:10

rifkinni