Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. 1) Reading an image in PIL gives a native PIL object.The size of the image is represented as width,height(PIL does not return channels)(400,300).This PIL object can be converted into numpy array by passing the PIL object to numpy.array().The returned object is a numpy array of shape attribute rows,columns,channels(300,400).Plotting both images in matplotlib gives rightly plotted image.
  2. ```
  3. import matplotlib.pyplot as plt
  4. from PIL import Image
  5. import numpy as np
  6.  
  7. img = Image.open('data/image.jpg').convert('L')
  8. print(img.size)#(400,300)
  9.  
  10. np_img = np.array(img)
  11. print(np_img.shape)#(300,400)
  12.  
  13. fig = plt.figure()
  14. ax1 = fig.add_subplot(121)
  15. ax2 = fig.add_subplot(122)
  16.  
  17. ax1.imshow(img,cmap='gray')
  18. ax2.imshow(np_img,cmap='gray')
  19.  
  20. plt.show()
  21.  
  22. ```
  23. 2) Reshape is a very dangerous command.The prime reason is as it can have many outputs.Input and output shape is simply not enough information to lock the output down to one option.What numpy does is,it first ravels the input tensor i.e. arranges its element in a 1d array and then arranges the output to required shape.
  24.  
  25. ```
  26. import numpy as np
  27. l = np.random.randint(1,10,(5,4,3))
  28. print(l)
  29. [[[5 1 2]
  30. # [2 9 7]
  31. # [9 2 9]
  32. # [6 8 1]]
  33. #
  34. # [[1 9 1]
  35. # [8 9 2]
  36. # [2 3 5]
  37. # [6 1 7]]
  38. #
  39. # [[3 1 8]
  40. # [2 6 7]
  41. # [4 5 9]
  42. # [2 9 3]]
  43. #
  44. # [[9 1 8]
  45. # [9 6 5]
  46. # [9 4 4]
  47. # [7 1 5]]
  48. #
  49. # [[2 7 8]
  50. # [1 7 6]
  51. # [1 3 1]
  52. # [6 2 1]]]
  53.  
  54.  
  55. print(np.reshape(l,(4,5,3)))
  56.  
  57. # [[[5 1 2]
  58. # [2 9 7]
  59. # [9 2 9]
  60. # [6 8 1]
  61. # [1 9 1]]
  62. #
  63. # [[8 9 2]
  64. # [2 3 5]
  65. # [6 1 7]
  66. # [3 1 8]
  67. # [2 6 7]]
  68. #
  69. # [[4 5 9]
  70. # [2 9 3]
  71. # [9 1 8]
  72. # [9 6 5]
  73. # [9 4 4]]
  74. #
  75. # [[7 1 5]
  76. # [2 7 8]
  77. # [1 7 6]
  78. # [1 3 1]
  79. # [6 2 1]]]
  80.  
  81.  
  82. ```
  83. If you want operations like flipping image by 90 deg etc,reshaping wont cut.You need to use things like transpose etc.
  84.  
  85. 3) `imshow` in matplotlib takes in negative pixel values too.For a grayscale image it has to plot pixel in range (0,255).The minimum pixel value in our image may be negative.It maps that negative velue to pure black and the maximum value to pure white.It divides (0,255) range in our new range of (0,|max|+|min|) and does plotting accordingly.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement