import acoustid import numpy as np import chromaprint popcnt_table_8bit = [ 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8, ] def popcnt(x): """ Count the number of set bits in the given 32-bit integer. """ return (popcnt_table_8bit[(x >> 0) & 0xFF] + popcnt_table_8bit[(x >> 8) & 0xFF] + popcnt_table_8bit[(x >> 16) & 0xFF] + popcnt_table_8bit[(x >> 24) & 0xFF]) def accuracy(fp1, fp2): error = 0 for x, y in zip(fp1, fp2): error += popcnt(x ^ y) return 1.0 - error / 32.0 / min(len(fp1), len(fp2)) def calc_accuracy(path1, path2): dur, fig = acoustid.fingerprint_file(path1) fp1 = chromaprint.decode_fingerprint(fig)[0] dur, fig2 = acoustid.fingerprint_file(path2) fp2 = chromaprint.decode_fingerprint(fig2)[0] return accuracy(fp1, fp2) if __name__ == '__main__': calc_accuracy(path1, path2)
时间: 2023-08-19 18:21:16 浏览: 56
import numpy as np(2).py
这段代码实现了计算两个音频文件的指纹相似度得分的功能。
首先,它定义了一个`popcnt()`函数,用于计算一个32位整数中二进制位为1的个数。该函数使用了一个查找表`popcnt_table_8bit`,该表中存储了一个8位整数中二进制位为1的个数,通过对32位整数进行拆分,再查找表中查找8位整数中二进制位为1的个数,最终将所有8位整数中二进制位为1的个数累加得到32位整数中二进制位为1的个数。
接着,它定义了一个`accuracy()`函数,该函数使用`popcnt()`函数计算两个指纹之间的汉明距离,并将汉明距离转换为相似度得分。汉明距离指的是两个等长字符串在对应位置上不同字符的个数,因此可以用来衡量两个指纹之间的相似度。
最后,它定义了一个`calc_accuracy()`函数,该函数使用`acoustid`模块和`chromaprint`模块计算每个音频文件的指纹,并将指纹转换为`chromaprint`格式。然后,它调用`accuracy()`函数计算指纹相似度得分,并将得分作为函数的返回值。
如果该代码是作为主程序执行的(即`__name__`等于`'__main__'`),则调用`calc_accuracy()`函数并传递音频文件的路径作为参数。需要注意的是,该代码中的`acoustid`和`chromaprint`模块需要通过pip安装。
阅读全文