I have a 3D grayscale image, and I want to compute an adaptive threshold function. In other words, I want to convert gray to binary, using one of the algorithms described here.
I tried to use cv2.adaptiveThreshold
, but it only works for 2D data.
This is my error:
cv2.error: OpenCV(4.11.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1679: error: (-215:Assertion failed) src.type() == CV_8UC1 in function 'cv::adaptiveThreshold'
I would suggest iterating over the first dimension and applying the adaptive threshold to each image slice:
import cv2
import numpy as np
# generate data and normalize to uint8
rng = np.random.default_rng()
data = rng.standard_normal((100,200,300))
data_normalized = cv2.normalize(src=data, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
# iterate over first dimension and apply adaptive threshold to each image
# the result is directly stored in the original data array
for i, img in enumerate(data_normalized):
data[i] = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)
This way, one direction gets neglected (the one you are iterating over), but it still might yield suitable results.