Advertisement
milanmetal

[Python] Image pixels np.tobytes

May 25th, 2018
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. # ===========================================================================
  2. # Generates binary representation of image pixels with some aditional
  3. # formatting
  4. #
  5. # newFileBytes = [123, 3, 255, 0, 100]
  6. # make file
  7. # newFile = open("filename.txt", "wb")
  8. # write to file
  9. # for byte in newFileBytes:
  10. #   newFile.write(byte.to_bytes(1, byteorder='big'))
  11. # ===========================================================================
  12.  
  13. import time
  14. import numpy as np
  15. import PIL
  16. from PIL import Image
  17. # fileHuman = open("pcie_img_human.txt","w")
  18. filePCIe = open("pcie_img.txt","w")
  19.  
  20. img_refs = []
  21.  
  22. #I = np.asarray(PIL.Image.open('test.jpg'))
  23. #x = np.ones((224, 224, 3), dtype='u1')
  24. img = Image.open("test.jpg")
  25. img = img.convert('RGB')        # You need this if you work with PNG
  26. pixels = img.load()             # create the pixel map
  27.  
  28. # Image dimensions
  29. img_width   = img.size[0]
  30. img_height  = img.size[1]
  31.  
  32. # nnzv = np.zeros(stick_num, dtype='u2')
  33. # nnzv[0:stick_num] = 0x0003
  34. # x = np.asarray(img, dtype='u1')
  35.  
  36. stick_num = 224*224
  37. x = np.zeros(stick_num*8, dtype='u2')
  38. for ix in range (0, img_width):
  39.     for iy in range (0, img_height):
  40.         stick_offset = (ix*img_height + iy)*8
  41.         x[stick_offset] = 0xe000
  42.         for j in range(3):
  43.             x[stick_offset + j] = pixels[ix,iy][j]
  44.  
  45. x.tobytes()
  46.  
  47. filePCIe.write(x)
  48. filePCIe.close()
  49. # https://stackoverflow.com/questions/2269827/how-to-convert-an-int-to-a-hex-string
  50. #    --------------->
  51. #   |
  52. #   |
  53. #   |
  54. #  \|/
  55. # for y in range (0, img_height):
  56. #   for x in range (0, img_width):
  57. #       # Extend tuple
  58. #       pixel = (pixels[x, y][0], pixels[x, y][1], pixels[x, y][2], 0)
  59. #       # line = " ".join(["\\{:s} \\0x00   ".format(hex(c)) for c in pixel])
  60. #       # Human readable
  61. #       line = "\\0xe0\\0x00 \\0x00\\0x00 \\0x00\\0x00 \\0x00\\0x00     ||  "
  62. #       line = line + " ".join(["\\0x{:02x} \\0x00  ".format(c) for c in pixel])
  63. #       fileHuman.write(line + "\n")
  64. #
  65. #       # Binary for PCIe
  66. #       line = "\\0xe0\\0x00\\0x00\\0x00\\0x00\\0x00\\0x00\\0x00"
  67. #       line = line + "".join(["\\0x{:02x}\\0x00".format(c) for c in pixel])
  68. #       filePCIe.write(line)
  69. #
  70. # fileHuman.close()
  71. # filePCIe.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement