cvbook icon indicating copy to clipboard operation
cvbook copied to clipboard

Consider using numpy.asarray() instead of numpy.array() for image conversion

Open SaFE-APIOpt opened this issue 9 months ago • 0 comments

https://github.com/nico/cvbook/blob/613f9059354147955334767148a559d6da8d0155/ocr.py#L23 In the line: im = numpy.array(Image.open(imname).convert('L')) it is recommended to use numpy.asarray() instead of numpy.array(). While both methods convert a PIL image to a NumPy array, numpy.array() always creates a copy of the data, whereas numpy.asarray() avoids copying when possible and returns a view if the input is already an array-compatible object.

Since Image.convert('L') returns a PIL image that supports buffer interface, numpy.asarray() can safely and efficiently convert it to an array without the additional overhead of copying, making the code slightly more efficient, especially when processing many images.

Suggested replacement: im = numpy.asarray(Image.open(imname).convert('L'))

SaFE-APIOpt avatar Mar 18 '25 02:03 SaFE-APIOpt