Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions av/video/frame.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,11 @@ cdef class VideoFrame(Frame):
image = useful_array(frame.planes[0]).reshape(frame.height, frame.width)
palette = np.frombuffer(frame.planes[1], 'i4').astype('>i4').reshape(-1, 1).view(np.uint8)
return image, palette
elif frame.format.name == 'nv12':
return np.hstack((
useful_array(frame.planes[0]),
useful_array(frame.planes[1], 2)
)).reshape(-1, frame.width)
else:
raise ValueError('Conversion to numpy array with format `%s` is not yet supported' % frame.format.name)

Expand Down Expand Up @@ -409,6 +414,17 @@ cdef class VideoFrame(Frame):
frame = VideoFrame(array.shape[1], array.shape[0], format)
copy_array_to_plane(byteswap_array(array, format == 'rgba64be'), frame.planes[0], 8)
return frame
elif format == 'nv12':
check_ndarray(array, 'uint8', 2)
check_ndarray_shape(array, array.shape[0] % 3 == 0)
check_ndarray_shape(array, array.shape[1] % 2 == 0)

frame = VideoFrame(array.shape[1], (array.shape[0] * 2) // 3, format)
uv_start = frame.width * frame.height
flat = array.reshape(-1)
copy_array_to_plane(flat[:uv_start], frame.planes[0], 1)
copy_array_to_plane(flat[uv_start:], frame.planes[1], 2)
return frame
else:
raise ValueError('Conversion from numpy array with format `%s` is not yet supported' % format)

Expand Down
16 changes: 16 additions & 0 deletions tests/test_videoframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,22 @@ def test_ndarray_pal8(self):
self.assertNdarraysEqual(returned[0], array)
self.assertNdarraysEqual(returned[1], palette)

def test_ndarray_nv12(self):
array = numpy.random.randint(0, 256, size=(720, 640), dtype=numpy.uint8)
frame = VideoFrame.from_ndarray(array, format="nv12")
self.assertEqual(frame.width, 640)
self.assertEqual(frame.height, 480)
self.assertEqual(frame.format.name, "nv12")
self.assertNdarraysEqual(frame.to_ndarray(), array)

def test_ndarray_nv12_align(self):
array = numpy.random.randint(0, 256, size=(357, 318), dtype=numpy.uint8)
frame = VideoFrame.from_ndarray(array, format="nv12")
self.assertEqual(frame.width, 318)
self.assertEqual(frame.height, 238)
self.assertEqual(frame.format.name, "nv12")
self.assertNdarraysEqual(frame.to_ndarray(), array)


class TestVideoFrameTiming(TestCase):
def test_reformat_pts(self):
Expand Down