Skip to content
This repository has been archived by the owner on Nov 17, 2023. It is now read-only.

Add bytearray support back to imdecode (#12855, #12868) #12912

Merged
merged 1 commit into from
Oct 25, 2018
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
11 changes: 8 additions & 3 deletions python/mxnet/image/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def imdecode(buf, *args, **kwargs):
Parameters
----------
buf : str/bytes or numpy.ndarray
buf : str/bytes/bytearray or numpy.ndarray
Binary image data as string or numpy ndarray.
flag : int, optional, default=1
1 for three channel color output. 0 for grayscale output.
Expand Down Expand Up @@ -135,10 +135,15 @@ def imdecode(buf, *args, **kwargs):
<NDArray 224x224x3 @cpu(0)>
"""
if not isinstance(buf, nd.NDArray):
if sys.version_info[0] == 3 and not isinstance(buf, (bytes, np.ndarray)):
raise ValueError('buf must be of type bytes or numpy.ndarray,'
if sys.version_info[0] == 3 and not isinstance(buf, (bytes, bytearray, np.ndarray)):
raise ValueError('buf must be of type bytes, bytearray or numpy.ndarray,'
'if you would like to input type str, please convert to bytes')
buf = nd.array(np.frombuffer(buf, dtype=np.uint8), dtype=np.uint8)

if len(buf) == 0:
# empty buf causes OpenCV crash.
raise ValueError("input buf cannot be empty.")

return _internal._cvimdecode(buf, *args, **kwargs)


Expand Down
16 changes: 16 additions & 0 deletions tests/python/unittest/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,22 @@ def test_imdecode(self):
cv_image = cv2.imread(img)
assert_almost_equal(image.asnumpy(), cv_image)

def test_imdecode_bytearray(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the tests should target exception handling.
Can you please also add a test that assertRaises if the buf is empty?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added two test cases, 2nd one is testing empty buffer case: test_imdecode_empty_buffer

try:
import cv2
except ImportError:
return
for img in TestImage.IMAGES:
with open(img, 'rb') as fp:
str_image = bytearray(fp.read())
image = mx.image.imdecode(str_image, to_rgb=0)
cv_image = cv2.imread(img)
assert_almost_equal(image.asnumpy(), cv_image)

@raises(ValueError)
def test_imdecode_empty_buffer(self):
mx.image.imdecode(b'', to_rgb=0)

def test_scale_down(self):
assert mx.image.scale_down((640, 480), (720, 120)) == (640, 106)
assert mx.image.scale_down((360, 1000), (480, 500)) == (360, 375)
Expand Down