Groovy 比较相似图片

文章目录
  1. 具体实现如下

参考文档:

直方图比较方法:
对输入的两张图像计算得到直方图H1和H2,归一化得到相同的尺度空间然后可以通过计算H1和H2之间的距离得到两个直方图相似程度进而比较图像本身的相似程度。

具体实现如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import javax.imageio.*
import java.awt.image.*
import java.awt.*
import java.io.*
import groovy.json.JsonBuilder

def photoDigest=new PhotoDigest()
photoDigest.process()

//直方图原理实现图像内容相似度比较
public class PhotoDigest {
/*
相似度超过99%以上,极其相似
相似度为:72%, 一般相似
*/
def process() {
def signatureList=generateSignation("/home/ice")
def currentFile="/home/ice/001.jpg"
def currentSignature=getSignation(new File(currentFile))
signatureList.each{
if (it.path!=currentFile){
def result=compare(currentSignature,it.signature)
if (result==100){
println("完全一致:${result}%, ${it.path}");
}else if (result>99){
println("极其相似:${result}%, ${it.path}");
}
}
}
}
//针对给定的目录生成所有图片的签名,并存储到指定路径下
def generateSignation(path){
def signatureList=[]
def scanFilePath=new File(path)
if (scanFilePath.exists()){
def signatureFile=new File(path+File.separator+"singature.json")
//如果存在,则直接载入文件内容
if (signatureFile.exists()){
signatureFile.eachLine{
def slurper = new groovy.json.JsonSlurper()
def json = slurper.parseText(it)
signatureList<<json
}
}else{//否则,扫描目录下所有图片,生成签名文件
def count=0
scanFilePath.eachFileRecurse(groovy.io.FileType.FILES, { file ->
def signature = new Expando(path:file.path, signature:getSignation(file))
signatureList<<signature
def builder = new JsonBuilder(signature)
def writer = new StringWriter()
builder.writeTo(writer)
signatureFile<<writer
signatureFile<<"\r\n"
count++
if (count.mod(500)==0) println "current process :${count}"
})
println "scan ${path} done. total: ${signatureList.size()}"
}
return signatureList
}else{
println "${path} is not exists."
}
}
//获取直方图签名
def getSignation(file) {
def img = ImageIO.read(file)
//转化图片到 100x100 ,参数:宽、高、类型
def slt = new BufferedImage(100, 100,BufferedImage.TYPE_INT_RGB)
slt.getGraphics().drawImage(img, 0, 0, 100, 100, null)
//ImageIO.write(slt,"jpeg",new File("slt.jpg"));
def data = new int[256]
for (int x = 0; x < slt.getWidth(); x++) {
for (int y = 0; y < slt.getHeight(); y++) {
int rgb = slt.getRGB(x, y)
Color myColor = new Color(rgb)
int r = myColor.getRed()
int g = myColor.getGreen()
int b = myColor.getBlue()
data[((r + g + b) / 3) as int]++
}
}
// data 就是所谓图形学当中的直方图的概念
return data
}
//输出相似度
def compare(src,dest) {
try {
def result = 0F
for (int i = 0; i < 256; i++) {
int abs = Math.abs(src[i] - dest[i])
int max = Math.max(src[i], dest[i])
result += (1 - ((float) abs / (max == 0 ? 1 : max)))
}
return (result / 256) * 100
} catch (Exception exception) {
return 0
}
}
}