Convert bits #250
-
Hello! I have a binary file with 10 bit pixels of a grayscale image, but in order to output it I need to convert it to 8 bit pixels or 16 bit pixels. I chose the option 10 -> 8 bits. I made this code, but the conversion takes a very long time. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
The biggest problem I can see is that you are opening and closing the output file for every single byte that you append to it. If you move the file open (line 11) to before the while loop it should speed up a lot (in my test it was about 30x faster). Rather than read in chunks of 10 bits and then manipulating it to throw away the final 2 bits, it might be faster to just read the 8 bits you want and advance the bit position by 2. Not sure on this as I haven't tested it. You can also use methods like cut() to divide into equal chunks more easily, and join() to join them back together. Rewriting should get a fair improvement - try something like this and let me know how you get on:
|
Beta Was this translation helpful? Give feedback.
-
I'm not sure why you're not seeing the same speed up that I did here. But as a side note, if you use PyPy instead of the standard CPython I get a >10x speed up (I'm using PyPy 7.3.9 - I think later versions might not be fully compatible). |
Beta Was this translation helpful? Give feedback.
I'm not sure why you're not seeing the same speed up that I did here. But as a side note, if you use PyPy instead of the standard CPython I get a >10x speed up (I'm using PyPy 7.3.9 - I think later versions might not be fully compatible).