如何使图像生成和哈希更有效?

2024-04-27 22:35:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用代码创建一个随机图像,然后检查该图像的哈希值,并将其与已知的哈希值进行比较。这是我的密码:

import os
import time
import hashlib
import numpy
from io import BytesIO
from PIL import Image

def create_image(width = 1920, height = 1080, num_of_images = 100):
    width = int(width)
    height = int(height)
    num_of_images = int(num_of_images)

    current = time.strftime("%Y%m%d%H%M%S")
    os.mkdir(current)
    i=0
    for n in range(num_of_images):
        filename = '{0}/{0}_{1:03d}.jpg'.format(current, n)
        rgb_array = numpy.random.rand(height,width,3) * 255
        image = Image.fromarray(rgb_array.astype('uint8')).convert('RGB')
        image.save(filename)
        imagee = open(filename, "rb").read()
        hashnum = hashlib.md5(imagee).hexdigest()

        if(hashnum=="B3D740C2F83F7EE120FD16EAED266B43"):
            image.save(filename)
            print(filename)
        else:
            os.remove(filename)
        i+=1
        print("Done with ", i, end='\r')

def main(args):
    create_image(width = args[0], height = args[1], num_of_images = args[2])
    return 0

if __name__ == '__main__':
    import sys 
    status = main(sys.argv[1:])
    sys.exit(status)

到目前为止,这个程序每秒要处理大约1k 17宽14高的图像,我想知道这是否更有效。我曾想过去掉整个保存图像,然后删除,但我真的不知道该怎么做。如果这篇文章有错误也很抱歉,英语不是我的第一语言


Tags: of图像imageimportosmainsysargs