作业一:编程设计电影海报的色彩

作业一:编程设计电影海报的色彩

作业一:设计电影海报的色彩可视化作品。模仿课程PPT第四章第43页上的1914年以来电影海报的颜色做进行可视化的作品,设计实现中国从2008年到2018年这十年间的国产电影海报的颜色可视化作品。具体要求如下:

  1. 采用Python语言编写从互联网上去获取自2008年-2018年中国国产电影的宣传海报图片的爬虫程序,并按年度分类存储;
  2. 针对这些图片,获取每幅图片上的每个像素的色彩值;
  3. 统计每幅海报图片中出现的像素颜色值数据;
  4. 纵坐标方向自上往下表示从2008年到2018年,横坐标表示当年电影海报中所包含的色彩(简单地以7色光为统计单位)
  5. 按自左至右红橙黄绿青蓝紫的顺序
  6. 对该作品进行一下感知和认知层面上的分析和解读
  7. 按本章课程PPT第四页的一般性流程,描述作品完成的过程及撰写体会

一、使用Python爬取1905网站的数据

此代码使用了zhaoolee写的爬取豆瓣TOP250的代码《进击的虫师》爬取豆瓣电影海报(Top250)

我在此基础上加了一点来实现老师的需求
import os
import requests
from lxml import etree
import re 

# 负责下载电影海报
def download_img(title, img_addr, headers, time):

    # 如果不存在图片文件夹,则自动创建
    if os.path.exists("./Top250_movie_images/"):
        pass
    else:
        os.makedirs("./Top250_movie_images/")
    if os.path.exists("./Top250_movie_images/" + time + "/"):
        pass
    else:
        os.makedirs("./Top250_movie_images/" + time + "/")

    # 获取图片二进制数据
    image_data = requests.get(img_addr, headers=headers).content
    # 设置海报存存储的路径和名称
    image_path = "./Top250_movie_images/" + time + "/" + title[0] + '.jpg'
    # 存储海报图片
    with open(image_path, "wb+") as f:
        f.write(image_data)


# 根据url获取数据,并打印到屏幕上,并保存为文件
def get_movies_data(url, headers):

    # 获取页面的响应内容
    db_response = requests.get(url, headers=headers)

    # 将获得的源码转换为etree
    db_reponse_etree = etree.HTML(db_response.content)

    # 提取所有电影数据
    db_movie_items = db_reponse_etree.xpath('//*[@class="fl line"]/a')
    print(len(db_movie_items))
    # 遍历电影数据列表,
    for db_movie_item in db_movie_items:

        # 这里用到了xpath的知识
        db_title = db_movie_item.xpath('img/@alt')
        print(db_title)
        db_date = db_movie_item.xpath('img/@data-original')
        db_img_addr = db_movie_item.xpath('img/@src')
        
        word = 'uploadfile' 
        index = [m.start() + 11 for m in re.finditer(word, str(db_date[0]))]
        print(index)
        db_movie_date = db_date[0][index[0]:index[0]+4]
        print("标题:", db_title[0]+" 时间:", db_movie_date + " URL:", db_date[0])
        # a表示追加模式, b表示以二进制方式写入, + 表示如果文件不存在则自动创建
        with open("./douban_movie_top250.txt", "ab+") as f:
            tmp_data = "标题:"+str(db_title)+ "-" + str(db_movie_date) + "\n"
            f.write(tmp_data.encode("utf-8"))

        db_img_addr = str(db_img_addr[0].replace("\'", ""))
        download_img(db_title, db_img_addr, headers, str(db_movie_date))


def main():
    # 使用列表生成式,生成待爬取的页面url的列表
    urls = []
    for i in range(5, 107):
        urls.append("http://www.1905.com/mdb/film/list/country-China/o0d0p"+str(i)+".html")
    # urls = ["[图片]http://www.1905.com/mdb/film/list/country-China/o0d0p"+str(i*1) for i in range(5,108)+".html"]

    # 设置请求头
    headers = {
        # 设置用户代理头
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
    }

    # 为避免重复运行程序,造成内容重复,这里把上次的文件清除(可跳过)
    if os.path.isfile("./douban_movie_top250.txt"):
        os.remove("./douban_movie_top250.txt")

    # 从列表取出url进行爬取
    for url in urls:
        get_movies_data(url, headers)

if __name__ == '__main__':
    main()

截图显示的是爬取的2008年到2019年的电影海报

二、针对这些图片,获取每幅图片上的每个像素的色彩值

  1. 使用list_all_files(’./Top250_movie_images’)遍历生成的海报
  2. 导入from PIL import Image并使用toRGB(name)对于每一张海报都生成对应的色彩值
  3. 使用data_write_csv(file_name, datas)或text_save(filename, data)生成对应的文件
from PIL import Image
import numpy
import csv
import codecs
import os
import re


def data_write_csv(file_name, datas):  # file_name为写入CSV文件的路径,datas为要写入数据列表
    file_csv = codecs.open(file_name, 'w+', 'utf-8')  # 追加
    writer = csv.writer(file_csv, delimiter=' ',
                        quotechar=' ', quoting=csv.QUOTE_MINIMAL)
    for data in datas:
        writer.writerow(data)
    print("保存文件成功,处理结束")


def text_save(filename, data):  # filename为写入CSV文件的路径,data为要写入数据列表.
    file = open(filename, 'a')
    for i in range(len(data)):
        s = str(data[i]).replace(
            '[', '').replace(']', '')  # 去除[],这两行按数据不同,可以选择
        s = s.replace("'", '').replace(',', '') + '\n'  # 去除单引号,逗号,每行末尾追加换行符
        file.write(s)
    file.close()
    print("保存文件成功")


def list_all_files(rootdir):
    import os
    _files = []
    list = os.listdir(rootdir)  # 列出文件夹下所有的目录与文件
    for i in range(0, len(list)):
        path = os.path.join(rootdir, list[i])
        if os.path.isdir(path):
            _files.extend(list_all_files(path))
        if os.path.isfile(path):
            _files.append(path)
            print(path)
            name = path[22:]
            toRGB(name)
            # print(name)
    return _files


def toRGB(name):
    time = name[:4]
    title = name[5:-4]
    
    print(title + " " + time)
    img = Image.open("C:\\Users\\Ifand\\Top250_movie_images\\" + name)
    img_array = img.load()
    width, height = img.size
    all_pixels = []
    for x in range(width):
        for y in range(height):
            cpixel = img_array[x, y]
            all_pixels.append(cpixel)
    # print(img_array[6, 4])
    print(len(all_pixels))

     # 如果不存在文件夹,则自动创建
    if os.path.exists("./Top250_movie_images/RGBFiles"):
        pass
    else:
        os.makedirs("./Top250_movie_images/RGBFiles")
    if os.path.exists("./Top250_movie_images/RGBFiles/" + time + "/"):
        pass
    else:
        os.makedirs("./Top250_movie_images/RGBFiles/" + time + "/")

    # data_write_csv("./Top250_movie_images/RGBFiles/" + time + "/" + title + ".csv", all_pixels)
    text_save("./Top250_movie_images/RGBFiles/" + time + "/" + title + ".txt", all_pixels)


def main():

    _fs = list_all_files('./Top250_movie_images')
    print(len(_fs))


if __name__ == '__main__':
    main()

如图所示是2008年的数据
未完待续
作业地址(GitHub)

猜你喜欢

转载自blog.csdn.net/sinat_27017647/article/details/89299257