https://github.com/willard-yuan/pcv-book-code-python2

https://github.com/jesolem/PCV-原版pcv

https://github.com/Li-Shu14/PCV-python3

https://github.com/jesolem/PCV/tree/gh-pages-pcv配套图片

https://github.com/willard-yuan/pcv-book-code


# -*- coding: utf-8 -*-from PIL import Image
import numpy as np
#from numpy import *
from matplotlib import pyplot as plt
#from pylab import *
from scipy.ndimage import filters
from PCV.tools import imtools
from PCV.tools.imtools import get_imlist
import os
import pickle
from PCV.tools import pca
from PCV.tools import rof
from scipy.ndimage import measurements, morphology# 添加中文字体支持
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"simsun.ttc", size=14)
#################1.1 PIL-Python图像库#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################plt.figure()pil_im = Image.open('data/empire.jpg')
plt.gray()
plt.subplot(121)
plt.title(u'原图',fontproperties=font)
plt.axis('off')
plt.imshow(pil_im)pil_im = Image.open('data/empire.jpg').convert('L')
plt.subplot(122)
plt.title(u'灰度图',fontproperties=font)
plt.axis('off')
plt.imshow(pil_im)plt.show()#################1.1.1 对图片进行格式转换#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################filelist = get_imlist('data/convert_images_format_test/') #获取convert_images_format_test文件夹下的图片文件名(包括后缀名)
imlist = open('data/convert_images_format_test/imlist.txt','wb') #将获取的图片文件列表保存到imlist.txt中
pickle.dump(filelist,imlist) #序列化
imlist.close()for infile in filelist:outfile = os.path.splitext(infile)[0] + ".png" #分离文件名与扩展名if infile != outfile:try:Image.open(infile).save(outfile)except IOError:print("cannot convert", infile)#################1.1.2 创建缩略图1.1.3 拷贝并粘贴区域1.1.4 调整尺寸及旋转#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################plt.figure()# 显示原图
pil_im = Image.open('data/empire.jpg')
print(pil_im.mode, pil_im.size, pil_im.format)
plt.subplot(231)
plt.title(u'原图', fontproperties=font)
plt.axis('off')
plt.imshow(pil_im)# 显示灰度图
pil_im = Image.open('data/empire.jpg').convert('L')
plt.gray()
plt.subplot(232)
plt.title(u'灰度图', fontproperties=font)
plt.axis('off')
plt.imshow(pil_im)#拷贝粘贴区域
pil_im = Image.open('data/empire.jpg')
box = (100,100,400,400)
region = pil_im.crop(box)
region = region.transpose(Image.ROTATE_180)
pil_im.paste(region,box)
plt.subplot(233)
plt.title(u'拷贝粘贴区域', fontproperties=font)
plt.axis('off')
plt.imshow(pil_im)# 缩略图
pil_im = Image.open('data/empire.jpg')
size = 128, 128
pil_im.thumbnail(size)
print(pil_im.size)
plt.subplot(234)
plt.title(u'缩略图', fontproperties=font)
plt.axis('off')
plt.imshow(pil_im)
pil_im.save('images/thumbnail.jpg') #保存缩略图# 调整图像尺寸
pil_im = Image.open('data/empire.jpg')
pil_im = pil_im.resize(size)
print(pil_im.size)
plt.subplot(235)
plt.title(u'调整尺寸后的图像', fontproperties=font)
plt.axis('off')
plt.imshow(pil_im)# 旋转图像45°
pil_im = Image.open('data/empire.jpg')
pil_im = pil_im.rotate(45)
plt.subplot(236)
plt.title(u'旋转45°后的图像', fontproperties=font)
plt.axis('off')
plt.imshow(pil_im)plt.show()#################1.2.1 画图、描点和线#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg'))
plt.figure()# 画有坐标轴的
plt.subplot(121)
plt.imshow(im)
x = [100, 100, 400, 400]
y = [200, 500, 200, 500]
plt.plot(x, y, 'r*')
plt.plot(x[:2], y[:2])
plt.title(u'绘图: "empire.jpg"', fontproperties=font)# 不显示坐标轴
plt.subplot(122)
plt.imshow(im)
x = [100, 100, 400, 400]
y = [200, 500, 200, 500]
plt.plot(x, y, 'r*')
plt.plot(x[:2], y[:2])
plt.axis('off')  #显示坐标轴
plt.title(u'绘图: "empire.jpg"', fontproperties=font)plt.show()#################1.2.2 图像轮廓和直方图#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg').convert('L'))  # 打开图像,并转成灰度图像plt.figure()
plt.subplot(121)
plt.gray()
plt.contour(im, origin='image')
plt.axis('equal')
plt.axis('off')
plt.title(u'图像轮廓', fontproperties=font)plt.subplot(122)
plt.hist(im.flatten(), 128)
plt.title(u'图像直方图', fontproperties=font)
plt.xlim([0,260])
plt.ylim([0,11000])plt.show()#################1.2.4 交互注释#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg'))
plt.imshow(im)
print('Please click 3 points')
plt.imshow(im)
#x = plt.ginput(3)
#print('You clicked:', x)
plt.show()#################1.3.1 图像数组表示#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg'))
print(im.shape, im.dtype)
im = np.array(Image.open('data/empire.jpg').convert('L'),'f')
print(im.shape, im.dtype)'''
im[i,:] = im[j,:] # set the values of row i with values from row j
im[:,i] = 100 # set all values in column i to 100
im[:100,:50].sum() # the sum of the values of the first 100 rows and 50 columns
im[50:100,50:100] # rows 50-100, columns 50-100 (100th not included)
im[i].mean() # average of row i
im[:,-1] # last column
im[-2,:] (or im[-2]) # second to last row
'''#################1.3.2 灰度变换#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg').convert('L'))
print(int(im.min()), int(im.max()))im2 = 255 - im  # invert image
print(int(im2.min()), int(im2.max()))im3 = (100.0/255) * im + 100  # clamp to interval 100...200
print(int(im3.min()), int(im3.max()))im4 = 255.0 * (im/255.0)**2  # squared
print(int(im4.min()), int(im4.max()))plt.figure()
plt.gray()
plt.subplot(1, 3, 1)
plt.imshow(im2)
plt.axis('off')
plt.title(r'$f(x)=255-x$')plt.subplot(1, 3, 2)
plt.imshow(im3)
plt.axis('off')
plt.title(r'$f(x)=\frac{100}{255}x+100$')plt.subplot(1, 3, 3)
plt.imshow(im4)
plt.axis('off')
plt.title(r'$f(x)=255(\frac{x}{255})^2$')
plt.show()#################1.3.3 直方图均衡化#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg').convert('L'))  # 打开图像,并转成灰度图像
#im = array(Image.open('../data/AquaTermi_lowcontrast.JPG').convert('L'))
im2, cdf = imtools.histeq(im)plt.figure()
plt.subplot(2, 2, 1)
plt.axis('off')
plt.gray()
plt.title(u'原始图像', fontproperties=font)
plt.imshow(im)plt.subplot(2, 2, 2)
plt.axis('off')
plt.title(u'直方图均衡化后的图像', fontproperties=font)
plt.imshow(im2)plt.subplot(2, 2, 3)
plt.axis('off')
plt.title(u'原始直方图', fontproperties=font)
#hist(im.flatten(), 128, cumulative=True, normed=True)
plt.hist(im.flatten(), 128, density=True)plt.subplot(2, 2, 4)
plt.axis('off')
plt.title(u'均衡化后的直方图', fontproperties=font)
#hist(im2.flatten(), 128, cumulative=True, normed=True)
plt.hist(im2.flatten(), 128, density=True)plt.show()#################1.3.4 图像平均#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################filelist = get_imlist('data/avg/') #获取convert_images_format_test文件夹下的图片文件名(包括后缀名)def imresize(im,sz):"""    Resize an image array using PIL. """pil_im = Image.fromarray(np.uint8(im))return np.array(pil_im.resize(sz))for impath in filelist:img=imresize(Image.open(impath), (600,800))import cv2dst = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)cv2.imwrite(impath, dst)avg = imtools.compute_average(filelist)for impath in filelist:im1 = np.array(Image.open(impath))plt.subplot(2, 2, filelist.index(impath)+1)plt.imshow(im1)imNum=str(filelist.index(impath)+1)plt.title(u'待平均图像'+imNum, fontproperties=font)plt.axis('off')
plt.subplot(2, 2, 4)
plt.imshow(avg)
plt.title(u'平均后的图像', fontproperties=font)
plt.axis('off')plt.show()#################1.3.5 对图像进行主成分分析#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^################## Uses sparse pca codepath.
#imlist = imtools.get_imlist('../data/selectedfontimages/a_selected_thumbs')# 获取图像列表和他们的尺寸
imlist = imtools.get_imlist('data/fontimages/a_thumbs')  # fontimages.zip is part of the book data set
im = np.array(Image.open(imlist[0]))  # open one image to get the size
m, n = im.shape[:2]  # get the size of the images
imnbr = len(imlist)  # get the number of images
print("The number of images is %d" % imnbr)# Create matrix to store all flattened images
immatrix = np.array([np.array(Image.open(imname)).flatten() for imname in imlist], 'f')# PCA降维
V, S, immean = pca.pca(immatrix)# Show the images (mean and 7 first modes)
# This gives figure 1-8 (p15) in the book.
plt.figure()
plt.gray()
plt.subplot(2, 4, 1)
plt.axis('off')
plt.imshow(immean.reshape(m, n))
for i in range(7):plt.subplot(2, 4, i+2)plt.imshow(V[i].reshape(m, n))plt.axis('off')
plt.show()#################1.3.6 Pickle模块#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^################## 保存均值和主成分
f = open('data/fontimages/font_pca_modes.pkl', 'wb')
pickle.dump(immean,f)
pickle.dump(V,f)
f.close()f = open('data/fontimages/font_pca_modes.pkl', 'wb')
pickle.dump(immean,f)
pickle.dump(V,f)
f.close()#################1.4.1 图像模糊#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg').convert('L'))plt.figure()
plt.gray()
plt.axis('off')
plt.subplot(1, 4, 1)
plt.axis('off')
plt.title(u'原图', fontproperties=font)
plt.imshow(im)for bi, blur in enumerate([2, 5, 10]):im2 = np.zeros(im.shape)im2 = filters.gaussian_filter(im, blur)im2 = np.uint8(im2)imNum=str(blur)plt.subplot(1, 4, 2 + bi)plt.axis('off')plt.title(u'标准差为'+imNum, fontproperties=font)plt.imshow(im2)#如果是彩色图像,则分别对三个通道进行模糊
#for bi, blur in enumerate([2, 5, 10]):
#  im2 = zeros(im.shape)
#  for i in range(3):
#    im2[:, :, i] = filters.gaussian_filter(im[:, :, i], blur)
#  im2 = np.uint8(im2)
#  subplot(1, 4,  2 + bi)
#  axis('off')
#  imshow(im2)
plt.show()#################1.4.2 图像差分#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg').convert('L'))
plt.gray()plt.subplot(1, 4, 1)
plt.axis('off')
plt.title(u'(a)原图', fontproperties=font)
plt.imshow(im)# Sobel derivative filters
imx = np.zeros(im.shape)
filters.sobel(im, 1, imx)
plt.subplot(1, 4, 2)
plt.axis('off')
plt.title(u'(b)x方向差分', fontproperties=font)
plt.imshow(imx)imy = np.zeros(im.shape)
filters.sobel(im, 0, imy)
plt.subplot(1, 4, 3)
plt.axis('off')
plt.title(u'(c)y方向差分', fontproperties=font)
plt.imshow(imy)#mag = numpy.sqrt(imx**2 + imy**2)
mag = 255-np.sqrt(imx**2 + imy**2)
plt.subplot(1, 4, 4)
plt.title(u'(d)梯度幅度', fontproperties=font)
plt.axis('off')
plt.imshow(mag)plt.show()#################高斯差分#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################def imx(im, sigma):imgx = np.zeros(im.shape)filters.gaussian_filter(im, sigma, (0, 1), imgx)return imgxdef imy(im, sigma):imgy = np.zeros(im.shape)filters.gaussian_filter(im, sigma, (1, 0), imgy)return imgydef mag(im, sigma):# there's also gaussian_gradient_magnitude()#mag = numpy.sqrt(imgx**2 + imgy**2)imgmag = 255 - np.sqrt(imgx ** 2 + imgy ** 2)return imgmagim = np.array(Image.open('data/empire.jpg').convert('L'))
plt.figure()
plt.gray()sigma = [2, 5, 10]for i in  sigma:plt.subplot(3, 4, 4*(sigma.index(i))+1)plt.axis('off')plt.imshow(im)imgx=imx(im, i)plt.subplot(3, 4, 4*(sigma.index(i))+2)plt.axis('off')plt.imshow(imgx)imgy=imy(im, i)plt.subplot(3, 4, 4*(sigma.index(i))+3)plt.axis('off')plt.imshow(imgy)imgmag=mag(im, i)plt.subplot(3, 4, 4*(sigma.index(i))+4)plt.axis('off')plt.imshow(imgmag)plt.show()#################1.4.3 形态学-物体计数#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^################## load image and threshold to make sure it is binary
plt.figure()
plt.gray()
im = np.array(Image.open('data/houses.png').convert('L'))
plt.subplot(221)
plt.imshow(im)
plt.axis('off')
plt.title(u'原图', fontproperties=font)
im = (im < 128)labels, nbr_objects = measurements.label(im)
print("Number of objects:", nbr_objects)
plt.subplot(222)
plt.imshow(labels)
plt.axis('off')
plt.title(u'标记后的图', fontproperties=font)# morphology - opening to separate objects better
im_open = morphology.binary_opening(im, np.ones((9, 5)), iterations=2)
plt.subplot(223)
plt.imshow(im_open)
plt.axis('off')
plt.title(u'开运算后的图像', fontproperties=font)labels_open, nbr_objects_open = measurements.label(im_open)
print("Number of objects:", nbr_objects_open)
plt.subplot(224)
plt.imshow(labels_open)
plt.axis('off')
plt.title(u'开运算后进行标记后的图像', fontproperties=font)plt.show()#################1.5 更高级的例子:图像降噪#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################
# create synthetic image with noise
im = np.zeros((500,500))
im[100:400,100:400] = 128
im[200:300,200:300] = 255
im = im + 30*np.random.standard_normal((500,500))U,T = rof.denoise(im,im)
G = filters.gaussian_filter(im,10)# save the result
#imsave('synth_original.pdf',im)
#imsave('synth_rof.pdf',U)
#imsave('synth_gaussian.pdf',G)# plot
plt.figure()
plt.gray()plt.subplot(1,3,1)
plt.imshow(im)
#axis('equal')
plt.axis('off')
plt.title(u'原噪声图像', fontproperties=font)plt.subplot(1,3,2)
plt.imshow(G)
#axis('equal')
plt.axis('off')
plt.title(u'高斯模糊后的图像', fontproperties=font)plt.subplot(1,3,3)
plt.imshow(U)
#axis('equal')
plt.axis('off')
plt.title(u'ROF降噪后的图像', fontproperties=font)plt.show()#################1.5 更高级的例子:图像降噪#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg').convert('L'))U,T = rof.denoise(im,im)
G = filters.gaussian_filter(im,10)# save the result
#imsave('synth_original.pdf',im)
#imsave('synth_rof.pdf',U)
#imsave('synth_gaussian.pdf',G)# plot
plt.figure()
plt.gray()plt.subplot(1,3,1)
plt.imshow(im)
#axis('equal')
plt.axis('off')
plt.title(u'原噪声图像', fontproperties=font)plt.subplot(1,3,2)
plt.imshow(G)
#axis('equal')
plt.axis('off')
plt.title(u'高斯模糊后的图像', fontproperties=font)plt.subplot(1,3,3)
plt.imshow(U)
#axis('equal')
plt.axis('off')
plt.title(u'ROF降噪后的图像', fontproperties=font)plt.show()#################------------------------#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^##################PIL的九种不同模式:1,L,P,RGB,RGBA,CMYK,YCbCr,I,F
#L 灰度模式
im = np.array(Image.open('data/empire.jpg').convert('L'))
plt.gray()
plt.subplot(1, 2, 1)
plt.axis('off')
plt.imshow(im)
sigma = 3
imx = np.zeros(im.shape)
imx = im + 0.4 * (im - filters.gaussian_filter(im, sigma))
#imx = filters.gaussian_filter(im, sigma)
#将数组a中的所有数限定到范围a_min和a_max中,
# 即a中所有比a_min小的数都会强制变为a_min,a中所有比a_max大的数都会强制变为a_max.
imx = np.clip(imx, 0, 255)
plt.subplot(1, 2, 2)
plt.axis('off')
plt.imshow(imx)
plt.show()#################------------------------#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################im = np.array(Image.open('data/empire.jpg').convert('L'))
#im = misc.lena()
im2, cdf = imtools.histeq(im)
im3 = np.uint8(255 * (im / (filters.gaussian_filter(im, 400) + 0.00001)))plt.figure()
plt.subplot(231)
plt.axis('off')
plt.gray()
plt.title('original')
plt.imshow(im)plt.subplot(234)
plt.axis('off')
plt.title('original hist')
#hist(im.flatten(), 128, cumulative=True, normed=True)
plt.hist(im.flatten(), 128, density=True)plt.subplot(232)
plt.axis('off')
plt.gray()
plt.title('histogram-equalized')
plt.imshow(im2)plt.subplot(235)
plt.axis('off')
plt.title('equalized hist')
#hist(im2.flatten(), 128, cumulative=True, normed=True)
plt.hist(im2.flatten(), 128, density=True)plt.subplot(233)
plt.axis('off')
plt.gray()
plt.title('quotient image')
plt.imshow(im3)plt.subplot(236)
plt.axis('off')
plt.title('quotient hist')
plt.hist(im3.flatten(), 128, density=True)
plt.show()
# -*- coding: utf-8 -*-import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
from PCV.localdescriptors import harris
from PCV.tools.imtools import imresize
from PCV.localdescriptors import sift
import sysimport json
import os
#python2中有urllib、urllib2、urlparse,但在python3中这些全部都被整合到了urllib中
import urllib
import urllib.request as ur
import urllib.parsefrom PCV.tools.imtools import get_imlist
from PCV.tools import imtools
import pydot# 添加中文字体支持
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"simsun.ttc", size=14)
# #################2.1 Harris角点检测#################
# #################************************#################
# #################$$$$$$$$$$$$$$$$$$$$$$$$#################
# #################@@@@@@@@@@@@@@@@@@@@@@@@#################
# #################^^^^^^^^^^^^^^^^^^^^^^^^#################
# # 读入图像
# im = np.array(Image.open('data/empire.jpg').convert('L'))
#
# # 检测harris角点
# harrisim = harris.compute_harris_response(im)
#
# # Harris响应函数
# harrisim1 = 255 - harrisim
#
# plt.figure()
# plt.gray()
#
# #画出Harris响应图
# plt.subplot(141)
# plt.imshow(harrisim1)
# print(harrisim1.shape)
# plt.axis('off')
# plt.axis('equal')
#
# threshold = [0.01, 0.05, 0.1]
# for i, thres in enumerate(threshold):
#     filtered_coords = harris.get_harris_points(harrisim, 6, thres)
#     plt.subplot(1, 4, i+2)
#     plt.imshow(im)
#     print(im.shape)
#     plt.plot([p[1] for p in filtered_coords], [p[0] for p in filtered_coords], '*')
#     plt.axis('off')
#
# #原书采用的PCV中PCV harris模块
# #harris.plot_harris_points(im, filtered_coords)
#
# # plot only 200 strongest
# # harris.plot_harris_points(im, filtered_coords[:200])
#
# plt.show()
#
#
# #################2.1.2 在图像间寻找对应点#################
# #################************************#################
# #################$$$$$$$$$$$$$$$$$$$$$$$$#################
# #################@@@@@@@@@@@@@@@@@@@@@@@@#################
# #################^^^^^^^^^^^^^^^^^^^^^^^^#################
#
# # Figure 2-2上面的图
# #im1 = array(Image.open("data/crans_1_small.jpg").convert("L"))
# #im2= array(Image.open("data/crans_2_small.jpg").convert("L"))
#
# # Figure 2-2下面的图
# im1 = np.array(Image.open("data/sf_view1.jpg").convert("L"))
# im2 = np.array(Image.open("data/sf_view2.jpg").convert("L"))
#
# # resize加快匹配速度
# im1 = imresize(im1, (int(im1.shape[1]/2), int(im1.shape[0]/2)))
# im2 = imresize(im2, (int(im2.shape[1]/2), int(im2.shape[0]/2)))
#
# wid = 5
# harrisim = harris.compute_harris_response(im1, 5)
# filtered_coords1 = harris.get_harris_points(harrisim, wid+1)
# d1 = harris.get_descriptors(im1, filtered_coords1, wid)
#
# harrisim = harris.compute_harris_response(im2, 5)
# filtered_coords2 = harris.get_harris_points(harrisim, wid+1)
# d2 = harris.get_descriptors(im2, filtered_coords2, wid)
#
# print('starting matching')
# matches = harris.match_twosided(d1, d2)
#
# plt.figure()
# plt.gray()
# harris.plot_matches(im1, im2, filtered_coords1, filtered_coords2, matches)
# plt.show()
#
#
# #################2.2 sift描述子#################
# #################************************#################
# #################$$$$$$$$$$$$$$$$$$$$$$$$#################
# #################@@@@@@@@@@@@@@@@@@@@@@@@#################
# #################^^^^^^^^^^^^^^^^^^^^^^^^#################
#
# imname = 'data/empire.jpg'
# im = np.array(Image.open(imname).convert('L'))
# sift.process_image(imname, './empire.sift')
# l1, d1 = sift.read_features_from_file('./empire.sift')
#
# plt.figure()
# plt.gray()
# plt.subplot(131)
# sift.plot_features(im, l1, circle=False)
# plt.title(u'SIFT特征',fontproperties=font)
# plt.subplot(132)
# sift.plot_features(im, l1, circle=True)
# plt.title(u'用圆圈表示SIFT特征尺度',fontproperties=font)
#
# # 检测harris角点
# harrisim = harris.compute_harris_response(im)
#
# plt.subplot(133)
# filtered_coords = harris.get_harris_points(harrisim, 6, 0.1)
# plt.imshow(im)
# plt.plot([p[1] for p in filtered_coords], [p[0] for p in filtered_coords], '*')
# plt.axis('off')
# plt.title(u'Harris角点',fontproperties=font)
#
# plt.show()
#
# #################2.2.4 描述子匹配#################
# #################************************#################
# #################$$$$$$$$$$$$$$$$$$$$$$$$#################
# #################@@@@@@@@@@@@@@@@@@@@@@@@#################
# #################^^^^^^^^^^^^^^^^^^^^^^^^#################
#
# #  im1f = '../data/sf_view1.jpg'
# #  im2f = '../data/sf_view2.jpg'
# im1f = 'data/crans_1_small.jpg'
# im2f = 'data/crans_2_small.jpg'
# #  im1f = '../data/climbing_1_small.jpg'
# #  im2f = '../data/climbing_2_small.jpg'
# im1 = np.array(Image.open(im1f))
# im2 = np.array(Image.open(im2f))
#
# sift.process_image(im1f, 'out_sift_1.txt')
# l1, d1 = sift.read_features_from_file('out_sift_1.txt')
# plt.figure()
# plt.gray()
# plt.subplot(121)
# sift.plot_features(im1, l1, circle=False)
#
# sift.process_image(im2f, 'out_sift_2.txt')
# l2, d2 = sift.read_features_from_file('out_sift_2.txt')
# plt.subplot(122)
# sift.plot_features(im2, l2, circle=False)
#
# #matches = sift.match(d1, d2)
# matches = sift.match_twosided(d1, d2)
# print('{} matches'.format(len(matches.nonzero()[0])))
#
# plt.figure()
# plt.gray()
# sift.plot_matches(im1, im2, l1, l2, matches, show_below=True)
# plt.show()#################图像序列显示#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################plt.figure()
plt.gray()
filelist = get_imlist('./data/001/')
for i, imlist in enumerate(filelist):im=Image.open(imlist)plt.subplot(4,5,i+1)plt.imshow(im)plt.axis('off')
plt.show()plt.figure()
plt.gray()
filelist = get_imlist('./data/002/')
for i, imlist in enumerate(filelist):im=Image.open(imlist)plt.subplot(4,5,i+1)plt.imshow(im)plt.axis('off')
plt.show()#################2.3.2 用局部描述子进行匹配#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################imlist = imtools.get_imlist('./data/002/')
nbr_images = len(imlist)# extract features
featlist = [imname[:-3] + 'sift' for imname in imlist]
for i, imname in enumerate(imlist):sift.process_image(imname, featlist[i])matchscores = np.zeros((nbr_images, nbr_images))for i in range(nbr_images):for j in range(i, nbr_images):  # only compute upper triangleprint('comparing ', imlist[i], imlist[j])l1, d1 = sift.read_features_from_file(featlist[i])l2, d2 = sift.read_features_from_file(featlist[j])matches = sift.match_twosided(d1, d2)nbr_matches = sum(matches > 0)print('number of matches = ', nbr_matches)matchscores[i, j] = nbr_matches
print("The match scores is: \n", matchscores)# copy values
for i in range(nbr_images):for j in range(i + 1, nbr_images):  # no need to copy diagonalmatchscores[j, i] = matchscores[i, j]
print(matchscores)
np.save("./matchscores.npy",matchscores)
np.save("./nbr_images.npy",nbr_images)
file = open('./imlist.txt', 'w')
for fp in imlist:file.write(str(fp))file.write('\n')
file.close()#################2.3.3 可视化接连的图片#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################g = pydot.Dot(graph_type='graph')
g.add_node(pydot.Node(str(0), fontcolor='transparent'))
for i in range(5):g.add_node(pydot.Node(str(i + 1)))g.add_edge(pydot.Edge(str(0), str(i + 1)))for j in range(5):g.add_node(pydot.Node(str(j + 1) + '0' + str(i + 1)))g.add_edge(pydot.Edge(str(j + 1) + '0' + str(i + 1), str(j + 1)))
g.write_png('./graph.png', prog='neato')#################2.3.3 可视化接连的图片#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################
file = open('./imlist.txt', 'r')
imlist = file.readlines()
for key in range(len(imlist)):imlist[key] = imlist[key].replace('\n','')
matchscores = np.load("matchscores.npy")
nbr_images = np.load("nbr_images.npy")pwd = os.getcwd()threshold = 2  # min number of matches needed to create link
g = pydot.Dot(graph_type='graph')  # don't want the default directed graph
for i in range(nbr_images):for j in range(i + 1, nbr_images):if matchscores[i, j] > threshold:# first image in pairim = Image.open(imlist[i])im.thumbnail((100, 100))filename = pwd + '/data/002/' + imlist[i].split('/')[-1].split('.')[0] + '.png'im.save(filename)  # need temporary files of the right sizeg.add_node(pydot.Node(str(i), fontcolor='transparent', shape='rectangle', image=filename))# second image in pairim = Image.open(imlist[j])im.thumbnail((100, 100))filename = pwd + '/data/002/' + imlist[j].split('/')[-1].split('.')[0] + '.png'#filename = path + str(j) + '.png'im.save(filename)  # need temporary files of the right sizeg.add_node(pydot.Node(str(j), fontcolor='transparent', shape='rectangle', image=filename))g.add_edge(pydot.Edge(str(i), str(j)))
g.write_png('./whitehouse.png')#################------------------------#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^##################################------------------------#################
#################************************#################
#################$$$$$$$$$$$$$$$$$$$$$$$$#################
#################@@@@@@@@@@@@@@@@@@@@@@@@#################
#################^^^^^^^^^^^^^^^^^^^^^^^^#################

计算机视觉编程-python3-ubuntu16.04相关推荐

  1. python3.6安装教程-Ubuntu16.04安装python3.6详细教程

    笔者最近在阿里云服务器上要搭建python3.6环境用于服务支撑,所以马不停蹄的就是安装python3.6,pip.一顿操作之后,发现坑还是有的,而且稍微有点麻烦,所以果断搬出了Anaconda,果不 ...

  2. python3.6.5安装-Ubuntu16.04安装python3.6.5详细步骤

    下载python3.6.5安装包 1. 上传安装包.打开终端,利用命令cd 进入文件所在文件夹里 python@ubuntu:~/workspace$pwd /home/python/workspac ...

  3. python3.6.5安装教程-Ubuntu16.04安装python3.6.5步骤详解

    下载python3.6.5安装包 1. 上传安装包.打开终端,利用命令cd 进入文件所在文件夹里 python@ubuntu:~/workspace$pwd /home/python/workspac ...

  4. Ubuntu16.04 python2.7升级python3.5

    2019独角兽企业重金招聘Python工程师标准>>> 正常情况下,你安装好ubuntu16.04版本之后,系统会自带 python2.7版本,如果需要下载新版本的python3.5 ...

  5. python3.8.3下载不了nltk_在ubuntu16.04+python3.5情况下安装nltk,以及gensim时pip3安装不成功的解决办法...

    在ubuntu16.04+python3.5情况下安装nltk,以及gensim时pip3安装不成功的解决办法,我刚开始因为不太会用linux命令,所以一直依赖于python 的pip命令,可是怎么都 ...

  6. DL之IDE:深度学习之计算机视觉开发环境搭建的详细流程(Ubuntu16.04+cuda9.0+cuDNN7.4.2+tensorflow_gpu)

    DL之IDE:深度学习之计算机视觉开发环境搭建的详细流程(Ubuntu16.04+cuda9.0+cuDNN7.4.2+tensorflow_gpu) 目录 1.安装nvidia驱动 2.安装CUDA ...

  7. python3.8.5是python3吗_科学网-Ubuntu16.04安装Python3.8.5问题及解决方法-陈超的博文

    Ubuntu16.04安装Python3.8.5: 安装编译之后出现apt-get错误You might want to run 'apt-get -f install' to correct the ...

  8. Ubuntu16.04怎样安装Python3.6

    Ubuntu16.04默认安装了Python2.7和3.5 请注意,系统自带的python千万不能卸载! 输入命令python 按Ctrl+D退出python命令行 输入命令sudo add-apt- ...

  9. ubuntu16.04 python3.5 opencv的安装与卸载(转载)

    转载https://blog.csdn.net/qq_37541097/article/details/79045595 Ubuntu16.04 自带python2.7和python3.5两个版本,默 ...

  10. 玩玩机器学习1——ubuntu16.04 64位安装TensorFlow GPU+python3+cuda8.0+cudnn8.0

    如今的机器学习运算大多数都是利用gpu进行,包括很大大型游戏,比特币的开采,都离不开GPU的运算,GPU已成为大型运算能力的主要硬件. 大名鼎鼎的机器学习开源框架,如TensorFlow和Caffe, ...

最新文章

  1. 人群距离监测 DeepSOCIAL 最全汉化论文+源码导读
  2. 重做实验七 寻址方式在结构化数据访问中的应用
  3. 每日程序C语言15-猴子吃桃问题
  4. 说说你对http、https、http2.0的理解【前端每日一题-25】
  5. 【渝粤题库】国家开放大学2021春1425调剂学(本)题目
  6. Linux基础之命令练习Day2-useradd(mod,del),groupadd(mod,del),chmod,chown,
  7. [html] 在两个iframe之间传递参数的方法有哪些?
  8. pytorch1.0神经网络保存、提取、加载
  9. Ubuntu 16.04 软件安装
  10. 烧了1.18亿美元融资后,谷歌GV投资的无人机公司宣布倒闭
  11. 指令篇:文件的创建和时间修改___touch
  12. 单元测试/集成测试/系统测试的区别
  13. CPC客户端离线升级失败,不能获取updatesipo信息,可能你的软件在线更新程序没有安装
  14. 电子海图与雷达图像的融合显示
  15. android短信分享,android 短信分享
  16. CentOS8 KVM USB设备直通虚拟机并实现热插拨
  17. OpenGL 实现视频编辑中的转场效果
  18. MBR与GPT分区的区别及使用注意事项(转载)
  19. 洛谷P1462 通往奥格瑞玛的道路 题解
  20. java自动化测试语言高级之HashSet

热门文章

  1. mysql中的char函数用法
  2. 抠图软件哪个最好用?这三款亲测简单、有效、功能强
  3. SLAM实操入门(七):使用Velodyne16线激光雷达与A-Loam进行三维SLAM
  4. 分不清ARM和X86架构,别跟我说你懂CPU!
  5. PMP学习(五):PMP学习的100个关键点
  6. 2019 蓝桥杯省赛 B 组模拟赛(一)
  7. js中如何拼接字符串
  8. SQLserver Distinct去重复的数据
  9. 黑色白色文字阴影HTML,利用css3的text-shadow属性实现文字阴影乳白效果
  10. F - Censor SCU - 4438(栈 + hash)