Currently the method Image.tobytes returns a byte string. There is nothing inherently bad about this, except that the returned bytes are read only (ofc) since bytes are immutable.
The consequence of this is that Image.__array__ does an extra copy when calling
|
return np.array(ArrayData(), dtype) |
that (I think) can be avoided. The data is copied from the immutable bytes string into a new mutable memory block around which the array is constructed.
This copy can be avoided in a few ways:
- Chance the code in
Image.__array__ to (roughly) np.frombuffer(self.tobytes(), dtype=dtype).reshape(shape). The downside is that the result is read-only (result.flags['WRITEABLE'] == False) which may be undesirable.
- Change the code in
Image.tobytes to return a bytearray. This may require work, depending on what encoder returns (didn't dive that far into the code), and it may be undesirable because type(Image.tobytes()) changes.
- Introduce a new
Image.tobytearray method that essentially mirrors Image.tobytes, except that it creates a mutable buffer. This resolves the problems that come with changing Image.tobytes return type, but may still need more work.
Would this be something interesting and/or useful to do?
Currently the method
Image.tobytesreturns a byte string. There is nothing inherently bad about this, except that the returned bytes are read only (ofc) since bytes are immutable.The consequence of this is that
Image.__array__does an extra copy when callingPillow/src/PIL/Image.py
Line 678 in a3d1e2f
that (I think) can be avoided. The data is copied from the immutable bytes string into a new mutable memory block around which the array is constructed.
This copy can be avoided in a few ways:
Image.__array__to (roughly)np.frombuffer(self.tobytes(), dtype=dtype).reshape(shape). The downside is that the result is read-only (result.flags['WRITEABLE'] == False) which may be undesirable.Image.tobytesto return abytearray. This may require work, depending on whatencoderreturns (didn't dive that far into the code), and it may be undesirable because type(Image.tobytes()) changes.Image.tobytearraymethod that essentially mirrorsImage.tobytes, except that it creates a mutable buffer. This resolves the problems that come with changingImage.tobytesreturn type, but may still need more work.Would this be something interesting and/or useful to do?