OpenCV: Can't process TOP data as CV_8UC1

I am having trouble getting some OpenCV functions to behave as they should. The example on the wiki uses goodFeaturesToTrack and works for me, but when I use OpenCV code that works fine outside of TouchDesigner, I have trouble ingesting the TOP.

In my onCook:

...
 topRef = scriptOp.par.Top.eval()
 img = topRef.numpyArray()
 img = img[:,:,:3]
 # the cvtColor on the next line SHOULD make the previous one unnecessary,
 # but I want to show that I've tried both approaches.
 img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 thresh = cv2.adaptiveThreshold(img, 255, 1, 1, 55, 2)
...

Excuting that last line results in the following error:

cv2.error: OpenCV(4.0.0)
C:\projects\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1507:
error: (-215:Assertion failed)
src.type() == CV_8UC1 in function 'cv::adaptiveThreshold'

The only workaround I’ve found is using OpenCV’s imread and imwrite to save and reopen img. This is, of course, impossibly slow.

Hey dahud,

this is because opencv expects images to be in 8bit.
Also opencv works in colors in 0-255 range, instead of 0-1 as TD does.
So replace this line:

img = topRef.numpyArray()

for

img = topRef.numpyArray()*255
img = img.astype(np.uint8)

Thank you! I managed to get to the bottom of this myself late last night.
For the record, here’s my full input processing routine:

        img = op("camMono").numpyArray()
        img = img[:,:,:3]

        img *= 255
        img = np.uint8(img)
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)