爱彼迎数据采集与预处理-图片色彩分析二

1 图片预处理

使用jupyter notebook对图片统一图片格式,等比例缩小图片尺寸。

import os,datetime
starttime = datetime.datetime.now()
from PIL import Image
from PIL import ImageFile

Image.MAX_IMAGE_PIXELS = 23000000000000  
ImageFile.LOAD_TRUNCATED_IMAGES = True

dirPath = r"图片地址"
save_d = r"缩小后图片存放地址"
 
allFile = os.listdir(dirPath)
for i in allFile:
  file = dirPath +"\" + i
  print(file)
  img = Image.open(file)
  img = img.convert(RGB)
  w,h = img.size
  newWidth = 200 #缩小后的宽度
  newHeight = round(newWidth / w * h)
  img = img.resize((newWidth,newHeight), Image.ANTIALIAS)
  img.save(save_d +"/" + i, optimize=True, quality=100)
endtime = datetime.datetime.now()
print(u本次处理共耗费 {}S .format((endtime - starttime).seconds))

2 提取图片相关数据(RGB值、HSV值等)

下载与安装color-summarizer。官网。下载后解压即可。

使用color-summarizer软件,在电脑后台运行,即点击win+R,输入cmd,找到文件路径,运行命令即可。

注:上图为找到文件路径。即下载后解压的位置。

bincolorsummarizer -dir "img_1-1000*jpg" -text >G:Download
ewyork_1-1000.txt

注:这里的.txt文件,可以改为.csv文件,以便后面通过excel来打开。

import csv
with open(r".txt文件位置", "r") as f:
    for line in f.readlines():
        line = line.strip(
) 
        ColourStr =line.split(" ")[:-3]
#         print(ColourStr)
        AllColour = ,.join(ColourStr)
        with open(r"保存.csv文件位置", a+, encoding=gbk) as f:
            f.write(str(AllColour)+ 
)

3 下载完成后,选择excel表格打开文件,结果包含了一张图片的四簇色彩,每簇色彩的像素值、占比、RGB、HEX、HSV、LAB、LCH、XYZ、CMYK、CIZE、CROP值。大致显示如下:

注:其他的下载命令可以参考color-summarizer官网,上面有教学。

经验分享 程序员 微信小程序 职场和发展