Python image processing

PIL: Python image processing library

  • Reading, gray, save:
from PIL import Image
# 打开一个图像,注意是当前路径:
im = Image.open('1.png')
# 灰度化处理
im = Image.open('1.png').convert('L')
# 保存灰度图像:
im.save('2.png')

 

We import the Imagemodule in python learning module , we will know that this will get the name of Imagethe object, the object contains a module im such a constant, and some other methods. If we have direct access to im, without Imageprefix what would happen?

Program throws an error called "NameError" of. This time we can use from this method can be directly used to achieve im this method. It will copy from the variable name to another scope, so it can use the variable names after copied directly in the script, rather than through the module.

  • Batch image format conversion
from PIL import Image
import os

def get_imlist(path):#获取文件名列表
    return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.png')]#读取png

filelist=get_imlist('C:/Users/Huawei/Desktop/EXP2/image')#建立一个列表对象
#print(filelist)
for infile in filelist:
  outfile = os.path.splitext(infile)[0] + ".jpg"#保存为jpg
  if infile != outfile:
    try:
      Image.open(infile).save(outfile)
    except IOError:
      print("cannot convert", infile)

 

Note that the file path delimiter is /

Only string is in double quotes, file name and file path are single quotes

  • Creating thumbnails
from PIL import Image
# 打开一个当前路径的图像:
im = Image.open('1.png')
im.thumbnail((128,128))
# 保存缩略图:
im.save('3.png')
  • copy and paste
from PIL import Image
# 打开一个当前路径的图像:
im = Image.open('1.png')
# 裁剪
box = (100,100,400,400)
region = im.crop(box)
# 旋转180度
region = region.transpose(Image.ROTATE_180)
# 粘贴
im.paste(region,box)
# 保存:
im.save('4.png')
  • Resizing and rotation
from PIL import Image
# 打开一个当前路径的图像:
im = Image.open('1.png')
# 调整尺寸
im = im.resize((128,128))
# 旋转
im = im.rotate(45)
# 保存:
im.save('5.png')

Matplotlib

Rendering image, points and lines

from PIL import Image
from pylab import *

im = Image.open('1.png')
 
# 绘制图像
imshow(im)#没有imshow(),show()将无法显示原图
axis('off')#不显示坐标轴
 
# x是横坐标,y是纵坐标:(100,200)(100,500)...
x = [100,100,400,400]
y = [200,500,600,800]
 
#绘制点或线
plot(x,y)         # 默认为蓝色实线
plot(x,y,'r*')    # 红色星状标记
plot(x,y,'go-')   # 带有圆圈标记的绿线
plot(x,y,'ks:')   # 带有正方形标记的黑色虚线

 
# 绘制连接前两个点的线
plot(x[:2],y[:2])#what?
 
# 添加标题
title('Plotting: "1.png"')
# 原图及绘制的点、线输出到屏幕
show()

Table 1-1: The PyLabcommand format basic color drawing library

colour

 

'b'

blue

'g'

green

'r'

red

'c'

Blue color

'm'

magenta

'y'

yellow

'k'

black

'w'

white

Table 1-2: The PyLabcommand line format basic drawing library

Linear

 

'-'

solid line

'--'

dotted line

':'

Dotted line

Table 1-3: The PyLabbasic rendering command format tag library drawing

mark

 

'.'

point

'o'

Circles

's'

square

'*'

Star

'+'

plus

'x'

Cross

Image contours and histograms

from PIL import Image
from pylab import *
 
# 读取图像到数组中,一定要读进数组,array(),否则无法绘制直方图(flatten)
im = array(Image.open('1.png').convert('L'))
 
# 新建一个图像
figure()

# 不使用颜色信息,灰度化
gray()

# 在原点的左上角显示轮廓图像
contour(im, origin='image')

# 坐标
axis('equal')
axis('off')

# 新建一个图像
figure()
# 图像的直方图可以使用 hist() 函数绘制
hist(im.flatten(),128)
show()

hist() Accept only one-dimensional array as input, so before we draw the image histogram, the image must be flattening process.

flatten() The method of any one-dimensional array is converted into an array in rows priority criteria.

 Interactive labeling

from PIL import Image
from pylab import *
 
im = Image.open('1.png')
#显示图片到屏幕
imshow(im)
print('Please click 3 points')
x = ginput(3)
print('you clicked:',x) 
show()#这个show()貌似没有用

The image array representation

When the image is loaded, by calling us  array() to convert the image into a method  NumPy of an array of objects

from PIL import Image
from pylab import *

im = array(Image.open('1.png'))
print (im.shape, im.dtype)
 
im = array(Image.open('1.png').convert('L'),'f')
print (im.shape, im.dtype)

First tuple each line represents the magnitude of an image array (rows, columns, color channel), followed by the string representation of the data type array elements. Because images are often encoded as an unsigned integer eight (uint8), so that in the first case, and converts it into an image to the array, the array is a data type "uint8". In the second case, the image is gray-scale processing, and the use of an additional parameter "f" when you create an array; parameter is converted to floating point data type.

Multiple array elements can be accessed using an array of slice manner. Slice the way return is based on the value of the element at a specified interval indexed access to the array. Here are some examples about the gray-scale image:

im[i,:] = im[j,:] # 将第 j 行的数值赋值给第 i 行
im[:,i] = 100 # 将第 i 列的所有数值设为100
im[:100,:50].sum() # 计算前100 行、前 50 列所有数值的和
im[50:100,50:100] # 50~100 行,50~100 列(不包括第 100 行和第 100 列)
im[i].mean() # 第 i 行所有数值的平均值
im[:,-1] # 最后一列
im[-2,:] (or im[-2]) # 倒数第二行

Gray-scale transformation

The image read into  NumPy the array object, we can perform any mathematical operations on them.

from PIL import Image
from pylab import *#imshow()show()
from numpy import *
 
im = array(Image.open('1.png').convert('L'))
 
im2 = 255 - im # 对图像进行反相处理
 
im3 = (100.0/255) * im + 100 # 将图像像素值变换到100...200 区间
 
im4 = 255.0 * (im/255.0)**2 # 对图像像素值求平方后得到的图像

imshow(im)
show()
imshow(im2)
show()
imshow(im3)
show()
imshow(im4)
show()

print (int(im.min()), int(im.max()))查看最小/最大 灰度值

Histogram equalization

from PIL import Image
from pylab import *

def histeq(im,nbr_bins=256):
  """ 对一幅灰度图像进行直方图均衡化"""
 
  # 计算图像的直方图
  imhist,bins = histogram(im.flatten(),nbr_bins,normed=True)
  cdf = imhist.cumsum() # cumulative distribution function
  cdf = 255 * cdf / cdf[-1] # 归一化
 
  # 使用累积分布函数的线性插值,计算新的像素值
  im2 = interp(im.flatten(),bins[:-1],cdf)
 
  return im2.reshape(im.shape), cdf


im = array(Image.open('1.png').convert('L'))  # 打开图像,并转成灰度图像
im2, cdf = histeq(im)
 
figure()
subplot(2, 2, 1)
axis('off')
gray()
title(u'Origin')
imshow(im)
 
subplot(2, 2, 2)
axis('off')
title(u'Processed')
imshow(im2)
 
subplot(2, 2, 3)
axis('off')
title(u'Origin Graph')
hist(im.flatten(), 128, normed=True)
 
subplot(2, 2, 4)
axis('off')
title(u'Processed Graph')
hist(im2.flatten(), 128, normed=True)
 
show()

# 添加中文字体支持
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)

title(u'原始图像', fontproperties=font)

The average image

from PIL import Image
from pylab import *#imshow()show()
from numpy import *
import os


def get_imlist(path):#获取文件名列表
    return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.png')]#读取png

def compute_average(imlist):
  """ 计算图像列表的平均图像"""
 
  # 打开第一幅图像,将其存储在浮点型数组中
  averageim = array(Image.open(imlist[0]), 'f')
 
  for imname in imlist[1:]:
    try:
      averageim += array(Image.open(imname))
    except:
      print (imname + '...skipped')
  averageim /= len(imlist)
 
  # 返回uint8 类型的平均图像
  return array(averageim, 'uint8')

filelist = get_imlist('C:/Users/Huawei/Desktop/EXP2/image')
avg = compute_average(filelist)

for impath in filelist:
        im1 = array(Image.open(impath))
        subplot(2, 2, filelist.index(impath)+1)
        imshow(im1)
        imNum=str(filelist.index(impath)+1)
        title(u'Origin'+imNum)
        axis('off')
subplot(2, 2, 4)
imshow(avg)
title(u'Processed')
axis('off')
 
show()

There are unresolved Warning

Published 115 original articles · won praise 9 · views 8118

Guess you like

Origin blog.csdn.net/weixin_43673589/article/details/104722225