Ask Your Question

# How do I convert uint8 to CV_8UC1 in OpenCV 3.2 Python?

The code is the following:

import numpy as np
import cv2
import time
from matplotlib import pyplot as plt

cv2.namedWindow( "Left", cv2.WINDOW_AUTOSIZE );
cv2.namedWindow( "Right", cv2.WINDOW_AUTOSIZE );

cam1 = cv2.VideoCapture(1)
cam1.set(cv2.CAP_PROP_FRAME_WIDTH,384)
cam1.set(cv2.CAP_PROP_FRAME_HEIGHT,216)

cam2 = cv2.VideoCapture(2)
cam2.set(cv2.CAP_PROP_FRAME_WIDTH,384)
cam2.set(cv2.CAP_PROP_FRAME_HEIGHT,216)

stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)

while(True):

# Capture frame-by-frame

ret, frame1 = cam1.read()

ret, frame2 = cam2.read()

# Display the resulting frame
cv2.imshow("Left",frame1)
cv2.imshow("Right",frame2)

disparity = stereo.compute(frame1,frame2) # kaput as it wants CV_8UC1 matrix
plt.imshow(disparity,'gray')
plt.show()

if cv2.waitKey(1) & 0xFF == ord('q'):
break

# When everything done, release the capture
cam1.release()
cam2.release()
cv2.destroyAllWindows()


Computing disparity is kaput as the image frame appears to be uint8 while the disparity computation wants CV_8UC1. Examples I have found to do the conversion are either in C++ or not in OpenCV 3.2 Pythonesque.

What is the conversion approach for uint8 to CV_8UC1 in OpenCV 3.2 Python please?

Cheers, A

edit retag close merge delete

## 1 answer

Sort by ยป oldest newest most voted

the images from your camera are uint8, too, but they are in color (3 channels), while you need grayscale (1 channel) images for the block matching. use cvtColor for the conversion:

# help(cv2.cvtColor)
gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
disparity = stereo.compute(gray1, gray2)

more

## Comments

1

Yep. I had worked this out in the background but I am still appreciative of the response by #berak as it also helps me understand why the code fixed the problem.

( 2017-06-11 01:55:43 -0500 )edit

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2017-06-10 22:27:04 -0500

Seen: 19,539 times

Last updated: Jun 11 '17