图像压缩/解压缩更改文件大小

2uluyalo  于 2021-06-09  发布在  Hbase
关注(0)|答案(0)|浏览(255)

编辑:底部的解决方案。
我正在做一个项目,每周都要把成千上万的图片存储到hadoop集群中,以便以后分析。我想把它们存储到hbase中,并找到了一个很好的管道来实现它。在使用hbase编写之前,我编写了一个程序,将图像转换为字节并存储到Dataframe中。问题是,当我从Dataframe中检索图像时,文件大小比原始文件大,我找不到原因。
我正在处理的图像大约是50kb,并保存为jpg格式。下面是将数据转换并存储到Dataframe中的代码:


# list_files contain a list with all the files' paths

list_bytes=[] #list for images in bytes
for i in range (0, len(list_files)):
    image_original = cv2.imread(list_files[i]) #get the image i from the file list
    flatten = image_original.flatten() #flatten the array for compression
    compress = bz2.compress(flatten) #bzip into bytes
    image_64bytes = base64.b64encode(compress) #change it to 64bytes
    list_bytes.append(image_64bytes) 
df=pd.DataFrame({'file':list_files, 'bytes':list_bytes}) #write images into a dataframe along with their metadata

下面是从中检索图像的代码 df :

decode = base64.b64decode(df.iloc[0,0])  #decode from 64bytes to bytes
unzip = bz2.decompress(decode) #unzip
conversion = np.frombuffer(unzip, dtype=np.uint8) #transform bytes into np.array
image_final = np.reshape(conversion, (650, 700,3)) #reshape image in its original format

为了证实 image_final 与相同 image_original 以下内容应返回空数组:

print((np.where((image_original == image_final ) == False)))

(数组([],dtype=int64)、数组([],dtype=int64)、数组([],dtype=int64))
然后我比较了存储在Dataframe中的以字节为单位的图像的大小,它似乎比原来的图像(50kb)大得多。我想这是意料之中的,但还是有很大的不同。

sys.getsizeof(df.iloc[0,0])

382129
如果我保存 image_final 在磁盘上 cv2.imwrite(file_path, image_final) 该文件的jpg格式为80kb,png格式为550kb。如果 image_original 以及 image_final 是相同的为什么磁盘上的大小不同?这可能是一个问题,以后当所有的图像将被加载进行分析。
事先谢谢你的帮助
注意:我也试过使用 cv2.imencode('.png', image_original)[1] / cv2.imdecode(conversion, cv2.IMREAD_COLOR) 而不是 image_original.flatten() / np.reshape(conversion, (650, 700,3)) 但结果非常相似。
编辑:不必加载图像并将其转换为字节,只需将文件读取为字节并将其保存到Dataframe中即可:


# list_files contain a list with all the files' paths

list_bytes=[]
for i in range (0, len(list_files)):
    in_file = open(list_files[i], "rb") # opening for [r]eading as [b]inary
    data = in_file.read() #insert bytes data into data
    compress = bz2.compress(data) #compress the data in bytes
    to_64bytes = base64.b64encode(compress) #change bytes to bytes64
    to_str = to_64bytes.decode() #transform as string for storage
    in_file.close()
    list_bytes.append(to_str) 
df=pd.DataFrame({'file':list_files, 'bytes':list_bytes}) #write it into a database with metadata

然后阅读图像:

s= df.iloc[0,1] #cell containing the string of the data to retrieve

decode = base64.b64decode(s) #transforms to byte64
unzip = bz2.decompress(decode) #unzip
conversion = np.frombuffer(unzip, dtype=np.uint8) #transform into np.array
img = cv2.imdecode(conversion, cv2.IMREAD_COLOR) #transform into img

plt.imshow(img)
plt.show()

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题