As the assertion states, adaptiveThreshold() requires a single-channeled 8-bit image.
Assuming your floating-point image ranges from 0 to 1, which appears to be the case, you can convert the image by multiplying by 255 and casting to np.uint8:
float_img = np.random.random((4,4))
im = np.array(float_img * 255, dtype = np.uint8)
threshed = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 0)
Answer from Aurelius on Stack OverflowAs the assertion states, adaptiveThreshold() requires a single-channeled 8-bit image.
Assuming your floating-point image ranges from 0 to 1, which appears to be the case, you can convert the image by multiplying by 255 and casting to np.uint8:
float_img = np.random.random((4,4))
im = np.array(float_img * 255, dtype = np.uint8)
threshed = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 0)
This one worked for me:
uint_img = np.array(float_arr*255).astype('uint8')
grayImage = cv2.cvtColor(uint_img, cv2.COLOR_GRAY2BGR)
Building a gray scale image via a numpy array from ultrasonic sensor values - programming - OpenCV
Grayscale image using opencv from numpy array failed - Stack Overflow
python 3.x - Applying CV2 Grayscale to a Numpy 4D array - Stack Overflow
python - cv2 - Load grayscale Image as Numpy Array from Variable - Stack Overflow
Let's say your 4D array of images is called img_stack with shape (60000,32,32,3).
You could do:
gray_stack = np.empty_like(img_stack[...,0])
for i in range(img_stack.shape[0]):
gray_stack[i] = cv2.cvtColor(img_stack[i], cv2.COLOR_RGB2GRAY)
Resulting shape is (60000,32,32).
Or you could do:
gray_stack = np.empty_like(img_stack[...,:1])
for i in range(img_stack.shape[0]):
gray_stack[i,:,:,0] = cv2.cvtColor(img_stack[i], cv2.COLOR_RGB2GRAY)
Resulting shape is (60000,32,32,1).
Bonus Tensorflow solution:
gray_stack = tf.image.rgb_to_grayscale(img_stack, name=None)
Resulting shape will be (60000,32,32,1).
The above OpenCV solutions might actually perform faster.
One more option using numpy:
grayscale_imgs = np.dot(img_stack, [0.299 , 0.587, 0.114])
grayscale_imgs.shape # => (60000, 32, 32)
More about the weighted sum can be found here