Basic image manipulation and processing using python
Preface:
Unlike the early days when most programs in computer vision were written in C/C++, researchers are considering the choice of language for implementing algorithms with more efficiency and ease of use. As computer hardware has become faster and faster, researchers have been considering the choice of language for implementing algorithms more in terms of the efficiency and ease of writing the code, rather than the efficiency of the algorithms as was the case in the early years. This is a direct result of the fact that in recent years, more and more researchers are choosing Python to implement their algorithms.
Today in the field of computer vision, more and more researchers use Python to carry out research, so it is necessary to learn the very easy to use python in the field of image processing, this blog will introduce how to use Python a few famous image processing libraries to complete the most basic image manipulation and processing.
Basic image manipulation using PIL
PIL Profile:
PIL (Python Imaging Library Python, image processing library) provides general-purpose image processing functions, as well as a large number of useful basic image operations, such as image scaling, cropping, rotation, color conversion and so on.
PIL reads and stores images:
Using the functions in PIL, we can read data from most image format files and write it to the most common image format files.The most important module in PIL is Image.
In the following program I use PIL to read a jpg image and save it as a png file after grayscaling it:
# -*- coding: utf-8 -*- from PIL import Image import os # Open an image to get a PIL image object img = ("./source/") # Turn it into a grayscale image img = ('L') #Store this image try: ("") except IOError: print "cannot convert"
PIL generates thumbnails:
# -*- coding: utf-8 -*- from PIL import Image import os # Open an image to get a PIL image object img = ("./source/") #Create thumbnails with 128 longest side ((128,128)) #Store this image try: ("") except IOError: print "cannot convert"
PIL resizing and rotation:
# -*- coding: utf-8 -*- from PIL import Image import os # Open an image to get a PIL image object img = ("./source/") # Modify the size of the image with a one-tuple parameter img = ((100,200)) # Make picture selection 45 degrees counterclockwise img = (45) #Store this image try: ("") except IOError: print "cannot convert"
PIL copy and paste the image area:
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- from PIL import Image import os # Open an image to get a PIL image object img = ("./source/") # Crop the specified area from img region = ((300,300,500,500)) # Make the cutout selection 145 degrees counterclockwise region = (145) # Paste the area into the designated area (region,(100,100,300,300)); #Store this image try: ("") except IOError: print "cannot convert"
In the use of tuples, the coordinate origin is the upper left corner and the region is divided as follows
Basic image manipulation using Matplotlib
Introduction to Matplotlib:
Matplotlib is a great library for doing math, drawing graphs, or plotting points, lines, and curves on images, and has much more powerful plotting capabilities than PIL. Matplotlib can draw good bar charts, pie charts, scatter plots, and so on, but for most computer vision applications, it's just a matter of a few plotting commands. For example, we want to use points and lines to represent things such as points of interest, correspondences, and detected objects.
Plotting images, points, and lines using Matplotlib
# -*- coding: utf-8 -*- from PIL import Image from pylab import * # Open an image to get a PIL image object img = ("./source/") # Read images into an array im = array(img) # Drawing images imshow(im) # Some points x = [100,100,400,400] y = [200,500,200,500] # Plot points using red star markers plot(x,y,'r*') # Draw the line connecting the first two points plot(x[:2],y[:2]) # Add a caption to show the drawn image title('Plotting: ""') show()
The show() command first opens a graphical user interface (GUI) and then creates a new image window. The GUI loops to block the script and then pauses until the last image window is closed. You can call the show() command only once per script, and usually at the end of the script.
You can also use the axis('off') command to make the axes not display.
running result
When drawing, there are many options to control the color and style of the image.
As:
plot(x,y) # Defaults to a solid blue line plot(x,y,'r*') # Red star markers plot(x,y,'go-') # Green line marked with a circle plot(x,y,'ks:') #Black dotted line with square markings
marking | color |
---|---|
‘b' | blue (color) |
‘g' | greener |
‘r' | red (color) |
‘c' | blue-green |
‘m' | magenta |
‘y' | yellow (color) |
‘k' | ferrous |
‘w' | fig. reactionary |
marking | linear |
---|---|
‘-‘ | solid line |
‘–' | dotted line |
‘:' | dotted line |
marking | geometry |
---|---|
‘.' | point (in space or time) |
‘o' | circle |
's' | square |
‘*' | ovals |
‘+' | plus sign + (math.) |
‘x' | crosses |
Plotting image contours using Matplotlib
Drawing contours of an image (or contour lines for other 2D functions) is very useful in your work. Since contouring requires the same threshold to be applied to each pixel value at coordinates [x, y], the image needs to be grayscaled first, and the contour image is then obtained using contour
# -*- coding: utf-8 -*- from PIL import Image from pylab import * # Read the image into an array and grayscale it im = array(('./source/').convert('L')) # Discard color information when displaying gray() # Display outline image contour(im, origin='image') # Displayed in the upper left corner of the origin axis('equal') # Close the axes axis('off') show()
running result
Plotting Histograms with Matplotlib
The histogram of an image is used to characterize the distribution of pixel values in that image. The range of characterized pixel values is specified by a certain number of bins, each of which yields the number of pixels that fall into the range represented by that bin. The histogram of a (grayscale) image can be plotted using the hist() function.
The second argument to the hist() function specifies the number of intervals. Note that since hist() accepts only one-dimensional arrays as input, we must flatten the image before plotting the image histogram. flatten() converts an arbitrary array into a one-dimensional array according to the row-first criterion.
# -*- coding: utf-8 -*- from PIL import Image from pylab import * # Read the image into an array and grayscale it im = array(('./source/').convert('L')) # Histogram images hist((),128) # Show show()
running result
Interactive Annotation with Matplotlib
The ginput() function in the PyLab library enables interactive labeling, which can be used to label some points or some training data.
# -*- coding: utf-8 -*- from PIL import Image from pylab import * # Read images into an array im = array(('./source/')) # Display image imshow(im) print 'Please click 3 points' # Get the click and save the click coordinates in the [x,y] list x = ginput(3) # Output saved data print 'you clicked:',x show()
The above script first draws an image and then waits for the user to click three times on the image area of the drawing window. The program automatically saves the coordinates [x, y] of these clicks in the x list.
running result
you clicked: [(295.22704081632651, 210.72448979591837), (405.43112244897952, 66.846938775510239), (439.1045918367347, 180.11224489795921)]
summarize
This blog introduces some python basic image manipulation, in addition to the above PIL and Matplotlib, but also often use numpy to directly manipulate the image array to achieve the purpose of manipulating the image, the use of scipy to complete more and more complex calculations, I will record my learning process, I hope to help you ~!
Above is the whole content of this article on python image routine operation, I hope it will help you. Interested friends can continue to refer to this site:
python constructing a graph using an adjacency matrix code example
Implementing CAPTCHA image code sharing in Python web
python fun project - pornographic image recognition code sharing
Python generate digital image code to share
Any questions can always leave a message, I will reply to everyone in time. Thank you friends for the support of this site!