Recently, I have been learning how to use python for image processing. I am constantly shocked by the efficiency of Python development. I also feel that developers pay attention to the efficiency during runtime, not only did I obviously feel more efficient when using version 2.5 than the original version 2.4, but even the new version of PIL significantly improved the image pixel operation efficiency.
The efficiency improvement in PIL mainly comes from the load function in the image module. This function is newly added in PIL 1.1.6, compared with the original getpixel and putpixel functions, the main purpose is to improve the efficiency of read/write operations on image data by providing image cache operation objects.
Here, we can use a simple example to compare the differences between the two methods. First, open an image file and create an image of the same size, then, copy the original image data to the new image pixel by pixel, Code As follows. This code runs on my machine. For images with an image resolution of 2048*1536, it only takes 5 seconds, if getpixel and putpixel functions are used for implementation (the Code commented out in the loop body), it takes 25 seconds. It can be seen that the load function improves the efficiency significantly. Import Image
Import Imagefilter
IMA = Image. Open ( ' Test.jpg ' )
Size = Ima. Size
IMB = Image. New ( ' RGB ' , Size)
Pima = Ima. Load ()
Pimb = IMB. Load ()
For I In Range (size [0]):
For J In Range (size [ 1 ]):
Pimb [I, j] = Pima [I, j] # Primb. putpixel (I, j), Pima. getpixel (I, j )))
IMB. Save ( ' Test.bmp ' )
In addition, it should be mentioned that the method for accelerating data reading and writing through the load function has been widely used in Pil. For example, it is a time-consuming filter function in the image module, the data cache object has been used to improve efficiency. The image. filter function is defined as follows: Def Filter (self, filter ):
" Apply environment filter to image "
Self. Load ()
From Imagefilter Import Filter
If Not Isinstance (filter, filter ):
Filter = Filter ()
If Self. Im. Bands = 1 :
Return Self. _ new (filter. Filter (self. Im ))
# Fix to handle multiband images since _ imaging doesn' t
IMS = []
For C In Range (self. Im. Bands ):
IMS. append (self. _ new (filter. Filter (self. Im. getband (c ))))
Return Merge (self. mode, IMS)