Using Python to manipulate images to achieve pixel access in images

Source: Internet
Author: User
This article mainly introduces the use of Python processing images to achieve the pixel access in the image, has a certain reference value, now share to everyone, the need for friends can refer to

In some of the previous examples, we used Image.open () to open an image and then manipulate the PiL object directly. If it's just a simple operation, but if the operation is slightly more complicated, it will be more difficult. So, usually when we load up the picture, we are converting the picture into a matrix for more complex operations.

Python uses the NumPy library and the SciPy library for various data manipulation and scientific calculations. We can install the two libraries directly via PIP.

Pip Install Numpypip Install scipy

Later, as long as the digital image processing in Python, we need to import these packages:

From PIL import Imageimport numpy as Npimport Matplotlib.pyplot as Plt

Open the image and turn it into a matrix and display:

From PIL import Imageimport numpy as Npimport Matplotlib.pyplot as Pltimg=np.array (Image.open (' d:/lena.jpg ')) # Open image and convert to digital matrix plt.figure ("Dog") Plt.imshow (IMG) plt.axis (' Off ') plt.show ()

Call the array () function in NumPy to convert the PiL object to an array object.

To view picture information, you can use the following methods:

Print img.shape print img.dtype print img.size print type (IMG)

If it is an RGB picture, then after converting to array, it becomes a rows*cols*channels three-dimensional matrix, so we can use Img[i,j,k] to access the pixel values.

Example 1: Open a picture and randomly add some salt and pepper noise

From PIL import Imageimport numpy as Npimport Matplotlib.pyplot as Pltimg=np.array (Image.open (' d:/ex.jpg ')) # Randomly generated 5,000 salt and pepper rows,cols,dims=img.shapefor I in range:  x=np.random.randint (0,rows)  Y=np.random.randint ( 0,cols)  img[x,y,:]=255  plt.figure ("Beauty") Plt.imshow (IMG) plt.axis (' Off ') plt.show ()

Example 2: The Lena image is binary, the pixel value is greater than 128 to 1, otherwise becomes 0

From PIL import Imageimport numpy as Npimport Matplotlib.pyplot as Pltimg=np.array (Image.open (' d:/pic/lena.jpg '). Convert (' L ')) rows,cols=img.shapefor I in range (rows):  to J in Range (cols):    if (img[i,j]<=128):      img[i, J]=0    Else:      img[i,j]=1      plt.figure ("Lena") plt.imshow (img,cmap= ' Gray ') plt.axis (' Off ') plt.show ()

If you want to manipulate multiple pixel points, you can access them using array slicing. The slice method returns the pixel value of the array that is accessed at the specified interval. Here are some examples of grayscale images:

Img[i:] = Im[j,:] # Assigns the value of line J to line I img[:,i] = 100 # Sets all values of column I to 100img[:100,:50].sum () # Calculates the first 100 rows, the first 50 columns of all values and img[50 : 100,50:100] # 50~100 row, 50~100 column (excluding rows 100th and 100th) Img[i].mean () # The average of all values in row I line img[:,-1] # last column img[-2,:] (or im[-2]) # pour Number two.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.