【问题标题】:Python : reduce execution time, optimize loopsPython:减少执行时间,优化循环
【发布时间】:2021-06-11 13:13:48
【问题描述】:
def SSIM_compute(files,WorkingFolder,DestinationAlikeFolder,DestinationUniqueFolder,results, start_time):
        
        NumberAlike=0
        loop=1
        while True:
            files=os.listdir(WorkingFolder)
            if files==[]:
                break
            IsAlike=False
            CountAlike=1
            print("Loop : "+str(loop)+" --- starttime : "+str(time.time()-start_time))
            
            for i in range (1,len(files)):
                #print("\ti= "+str(i)+" : "+str(time.time()-start_time))
                img1=cv2.imread(WorkingFolder+"/"+files[0])
                img2=cv2.imread(WorkingFolder+"/"+files[i])
                x1,y1=img1.shape[:2]
                x2,y2=img2.shape[:2]
                x=min(x1,x2)
                y=min(y1,y2)         
                img1=cv2.resize(img1,(x,y),1)
                img2=cv2.resize(img2,(x,y),1)
                threshold=ssim(img1,img2,multichannel=True)
                if threshold>0.8:
                    IsAlike=True
                    if os.path.exists((WorkingFolder+"/"+files[i])):
                        shutil.move((WorkingFolder+"/"+files[i]),DestinationAlikeFolder+"/alike"+str(NumberAlike)+"_"+str(CountAlike)+".jpg") 
                        CountAlike+=1
                        #results.write("ALIKE : " +files[0] +" --- " +files[i]+"\n")
                        results.write("ALIKE : /alike"+str(NumberAlike)+"_0"+".jpg --- /alike"+str(NumberAlike)+"_"+str(CountAlike)+".jpg  -> "+str(threshold))
                        
            if IsAlike:
                if os.path.exists((WorkingFolder+"/"+files[0])):
                    shutil.move((WorkingFolder+"/"+files[0]),DestinationAlikeFolder+"/alike"+str(NumberAlike)+"_0"+".jpg")  
                    NumberAlike+=1
            else :
                if os.path.exists((WorkingFolder+"/"+files[0])):
                    shutil.move((WorkingFolder+"/"+files[0]),DestinationUniqueFolder)
            loop+=1  

我有这段代码,它必须比较图像以确定它们是否相同或其中一些是否被修改(压缩、伪像等)。

因此,为了检查两个图像是否严格相似,我只需计算并比较它们各自的哈希值(在此处未显示的另一个函数中),并检查它们是否相似,我计算这两个文件的 SSIM。

下一部分是麻烦开始的地方:当我在一组安静的小图片(大约 50 张)上测试这段代码时,执行时间还不错,但是如果我将图片集更大(大约 200 张图片),考虑到我有两个重叠的 for 循环,执行时间变得像预期的那样太长(几个小时)。

由于我不是很有创意,有没有人想在更大的数据集上减少执行时间?也许是一种避免那些重叠循环的方法?

感谢您提供的任何帮助:)

【问题讨论】:

    标签: python optimization execution-time


    【解决方案1】:

    您正在将每张图片与其他每张图片进行比较 - 您可以从 for 循环中拉出读取第一张图片 img1 并为每个文件执行一次。

    但是,当您将每个文件与每个其他文件进行比较时,该文件将减慢为 O(N^2/2),即 200 将比 50 慢 8 倍。也许您可以调整为更小的尺寸,如 64x64,这将与ssim() 进行比较会快得多,并且只有在小尺寸相似的情况下才能进行全尺寸比较?

    【讨论】:

    • 感谢您的建议,我会尝试并根据获得的时间更新帖子。看了一些文章后我也在考虑使用线程,如果我实现了它,我也会提供有关它的消息
    猜你喜欢
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 2012-11-09
    • 2019-10-07
    • 2020-02-10
    相关资源
    最近更新 更多