img2txt icon indicating copy to clipboard operation
img2txt copied to clipboard

Possible numpy code optimazation

Open rien333 opened this issue 6 years ago • 0 comments

The code that maps rgb pixel inputs to ascii characters in the generate_grayscale_for_image() function can be written more efficiently by using matrix calculations from numpy. Currently, it looks like this:

for h in range(height):
      for w in range(width):
          rgba = pixels[w, h]
          if rgba[3] != 255 and bgcolor is not None:
              rgba = alpha_blend(rgba, bgcolor)
			# ...
        rgb = rgba[:3]
        string += color[int(sum(rgb) / 3.0 / 256.0 * 16)]
    string += "\n

The calculation int(sum(rgb) / 3.0 / 256.0 * 16) in the inner-body of the loop can be done on the pixels input variable when it's represented as a matrix. The code will likely become less readable, but a comment could be added to elaborate on the new calculations. With this optimization in place, I was able to build a program that converts webcam input images to ascii text with a really decent framerate.

rien333 avatar Dec 05 '17 16:12 rien333