方法一:
#!C:/Python27
#coding=utf-8
import pytesseract
from pytesser import *
from PIL import Image,ImageEnhance,ImageFilter
import os
import fnmatch
import re,time
import urllib, random
#import hashlib
def getGray(image_file):
tmpls=[]
for h in range(0, image_file.size[1]):#h
for w in range(0, image_file.size[0]):#w
tmpls.append( image_file.getpixel((w,h)) )
return tmpls
def getAvg(ls):#获取平均灰度值
return sum(ls)/len(ls)
def getMH(a,b):#比较100个字符有几个字符相同
dist = 0;
for i in range(0,len(a)):
if a[i]==b[i]:
dist=dist+1
return dist
def getImgHash(fne):
image_file = Image.open(fne) # 打开
image_file=image_file.resize((12, 12))#重置图片大小我12px X 12px
image_file=image_file.convert("L")#转256灰度图
Grayls=getGray(image_file)#灰度集合
avg=getAvg(Grayls)#灰度平均值
bitls=''#接收获取0或1
#除去变宽1px遍历像素
for h in range(1, image_file.size[1]-1):#h
for w in range(1, image_file.size[0]-1):#w
if image_file.getpixel((w,h))>=avg:#像素的值比较平均值 大于记为1 小于记为0
bitls=bitls+'1'
else:
bitls=bitls+'0'
return bitls
'''
m2 = hashlib.md5()
m2.update(bitls)
print m2.hexdigest(),bitls
return m2.hexdigest()
'''
a=getImgHash(".//testpic//001n.bmp")#图片地址自行替换
files = os.listdir(".//testpic")#图片文件夹地址自行替换
for file in files:
b=getImgHash(".//testpic//"+str(file))
compare=getMH(a,b)
print file,u'相似度',str(compare)+'%'
#!C:/Python27
#coding=utf-8
# 原作者发布在GitHub上的一些列图片对比的方法。有兴趣研究的可以访问链接如下:
# https://github.com/MashiMaroLjc/Learn-to-identify-similar-images
# coding : utf-8
from PIL import Image
def calculate(image1, image2):
g = image1.histogram()
s = image2.histogram()
assert len(g) == len(s), "error"
data = []
for index in range(0, len(g)):
if g[index] != s[index]:
data.append(1 - abs(g[index] - s[index]) / max(g[index], s[index]))
else:
data.append(1)
return sum(data) / len(g)
def split_image(image, part_size):
pw, ph = part_size
w, h = image.size
sub_image_list = []
assert w % pw == h % ph == 0, "error"
for i in range(0, w, pw):
for j in range(0, h, ph):
sub_image = image.crop((i, j, i + pw, j + ph)).copy()
sub_image_list.append(sub_image)
return sub_image_list
def classfiy_histogram_with_split(image1, image2, size=(256, 256), part_size=(64, 64)):
'''
'image1' 和 'image2' 都是Image 对象.
可以通过'Image.open(path)'进行创建。
'size' 重新将 image 对象的尺寸进行重置,默认大小为256 * 256 .
'part_size' 定义了分割图片的大小.默认大小为64*64 .
返回值是 'image1' 和 'image2'对比后的相似度,相似度越高,图片越接近,达到100.0说明图片完全相同。
'''
img1 = image1.resize(size).convert("RGB")
sub_image1 = split_image(img1, part_size)
img2 = image2.resize(size).convert("RGB")
sub_image2 = split_image(img2, part_size)
sub_data = 0
for im1, im2 in zip(sub_image1, sub_image2):
sub_data += calculate(im1, im2)
x = size[0] / part_size[0]
y = size[1] / part_size[1]
pre = round((sub_data / (x * y)), 6)
print u"相似度为:",(pre * 100)
return pre * 100
if __name__ == '__main__':
image1 = Image.open(".//testpic//new.png")
image2 = Image.open(".//testpic//new.png")
classfiy_histogram_with_split(image1, image2)
方法三: 需要安装第三方包 ,针对window用户,切换到python安装目录下的script目录下,按住shift+右键,在此处打开cmd命令窗口
输入命令:pip install requests 来安装request 模块,其他模块也一样
pip install numpy
pip install matplotlib
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import cv2
from math import log
from PIL import Image
import datetime
import pywt
# 以下强行用Python宏定义变量
halfWindowSize=9
src1_path = './/testpic//new.png'
src2_path = './/testpic//new.png'
'''''
来自敬忠良,肖刚,李振华《图像融合——理论与分析》P85:基于像素清晰度的融合规则
1,用Laplace金字塔或者是小波变换,将图像分解成高频部分和低频部分两个图像矩阵
2,以某个像素点为中心开窗,该像素点的清晰度定义为窗口所有点((高频/低频)**2).sum()
3,目前感觉主要的问题在于低频
4,高频取清晰度图像中较大的那个图的高频图像像素点
5,算法优化后速度由原来的2min.44s.变成9s.305ms.
补充:书上建议开窗大小10*10,DWT取3层,Laplace金字塔取2层
'''
def imgOpen(img_src1,img_src2):
apple=Image.open(img_src1).convert('L')
orange=Image.open(img_src2).convert('L')
appleArray=np.array(apple)
orangeArray=np.array(orange)
return appleArray,orangeArray
# 严格的变换尺寸
def _sameSize(img_std,img_cvt):
x,y=img_std.shape
pic_cvt=Image.fromarray(img_cvt)
pic_cvt.resize((x,y))
return np.array(pic_cvt)
# 小波变换的层数不能太高,Image模块的resize不能变换太小的矩阵,不相同大小的矩阵在计算对比度时会数组越界
def getWaveImg(apple,orange):
appleWave=pywt.wavedec2(apple,'haar',level=4)
orangeWave=pywt.wavedec2(orange,'haar',level=4)
lowApple=appleWave[0];lowOrange=orangeWave[0]
# 以下处理低频
lowAppleWeight,lowOrangeWeight = getVarianceWeight(lowApple,lowOrange)
lowFusion = lowAppleWeight*lowApple + lowOrangeWeight*lowOrange
# 以下处理高频
for hi in range(1,5):
waveRec=[]
for highApple,highOrange in zip(appleWave[hi],orangeWave[hi]):
highFusion = np.zeros(highApple.shape)
contrastApple = getContrastImg(lowApple,highApple)
contrastOrange = getContrastImg(lowOrange,highOrange)
row,col = highApple.shape
for i in xrange(row):
for j in xrange(col):
if contrastApple[i,j] > contrastOrange[i,j]:
highFusion[i,j] = highApple[i,j]
else:
highFusion[i,j] = highOrange[i,j]
waveRec.append(highFusion)
recwave=(lowFusion,tuple(waveRec))
lowFusion=pywt.idwt2(recwave,'haar')
lowApple=lowFusion;lowOrange=lowFusion
return lowFusion
# 求Laplace金字塔
def getLaplacePyr(img):
firstLevel=img.copy()
secondLevel=cv2.pyrDown(firstLevel)
lowFreq=cv2.pyrUp(secondLevel)
highFreq=cv2.subtract(firstLevel,_sameSize(firstLevel,lowFreq))
return lowFreq,highFreq
# 计算对比度,优化后不需要这个函数了,扔在这里看看公式就行
def _getContrastValue(highWin,lowWin):
row,col = highWin.shape
contrastValue = 0.00
for i in xrange(row):
for j in xrange(col):
contrastValue += (float(highWin[i,j])/lowWin[i,j])**2
return contrastValue
# 先求出每个点的(hi/lo)**2,再用numpy的sum(C语言库)求和
def getContrastImg(low,high):
row,col=low.shape
if low.shape!=high.shape:
low=_sameSize(high,low)
contrastImg=np.zeros((row,col))
contrastVal=(high/low)**2
for i in xrange(row):
for j in xrange(col):
up=i-halfWindowSize if i-halfWindowSize>0 else 0
down=i+halfWindowSize if i+halfWindowSize0 else 0
right=j+halfWindowSize if j+halfWindowSize contrastOrange[i,j] else highOrange[i,j]
# 开始重建
fusionResult = cv2.add(highFusion,lowFusion)
return fusionResult
# 绘图函数
def getPlot(apple,orange,result):
plt.subplot(131)
plt.imshow(apple,cmap='gray')
plt.title('src1')
plt.axis('off')
plt.subplot(132)
plt.imshow(orange,cmap='gray')
plt.title('src2')
plt.axis('off')
plt.subplot(133)
plt.imshow(result,cmap='gray')
plt.title('result')
plt.axis('off')
plt.show()
# 画四张图的函数,为了方便同时比较
def cmpPlot(apple,orange,wave,pyr):
plt.subplot(221)
plt.imshow(apple,cmap='gray')
plt.title('SRC1')
plt.axis('off')
plt.subplot(222)
plt.imshow(orange,cmap='gray')
plt.title('SRC2')
plt.axis('off')
plt.subplot(223)
plt.imshow(wave,cmap='gray')
plt.title('WAVELET')
plt.axis('off')
plt.subplot(224)
plt.imshow(pyr,cmap='gray')
plt.title('LAPLACE PYR')
plt.axis('off')
plt.show()
def runTest(src1=src1_path,src2=src2_path,isplot=True):
apple,orange=imgOpen(src1,src2)
beginTime=datetime.datetime.now()
print(beginTime)
waveResult=getWaveImg(apple,orange)
pyrResult=getPyrFusion(apple,orange)
endTime=datetime.datetime.now()
print(endTime)
print('Runtime: '+str(endTime-beginTime))
if isplot:
cmpPlot(apple,orange,waveResult,pyrResult)
return waveResult,pyrResult
if __name__=='__main__':
runTest()
#!C:/Python27
#coding=utf-8
import pytesseract
from pytesser import *
from PIL import Image,ImageEnhance,ImageFilter
import os
import fnmatch
import re,time
import urllib, random
onepng = ('.//testpic//001n.bmp')
twopng = ('.//testpic//001n.png')
def fixed_size():
"""按照固定尺寸处理图片"""
im1 = Image.open('.//testpic//001n.bmp')
im2 = Image.open('.//testpic//000n.bmp')
width, height = im1.size
diff = [(x, y) for x in xrange(width) for y in xrange(height) if im1.getpixel((x, y)) != im2.getpixel((x, y))]
print u"打印值:",len(diff)
fixed_size()