适配器绘制图片,gif

总代码

import os
import cv2
import abc
import random
import glob
import jieba
import imageio
import librosa
import librosa.display
from PIL import Image
import math
import pandas as pd
from sklearn.decomposition import PCA

'''
对于适配器来说两种方式
一种抽象类,规定类的方法
一种采用
'''
import matplotlib.pyplot as plt
from wordcloud import WordCloud

class Plotter(abc.ABC):#构造抽象类Plotter
    @abc.abstractmethod
    def plot(self,*args,**kwargs):
        pass

class PointPlotter(Plotter):
    def __init__(self,lis_point):
        self.point=lis_point
    def plot(self):
        x=[]
        y=[]
        for a,b in self.point:
            x.append(a)
            y.append(b)
        plt.scatter(x,y)
        plt.xlabel("point_x")
        plt.ylabel("point_y")
        plt.title("Draw Point")
        plt.savefig("./1.png")

class ArrayPlotter(Plotter):
    def __init__(self,lis_point):
        self.point=lis_point

    def plot(self):
        if len(self.point)==2:
            x=self.point[0]
            y=self.point[1]
            plt.scatter(x,y)
            plt.xlabel("x")
            plt.ylabel("y")
            plt.title("ArrayPlotter")
            plt.savefig("./2.png")
        elif len(self.point)==3:
            ax=plt.subplot(projection='3d')#创建一个3d工程
            x=self.point[0]
            y=self.point[1]
            z=self.point[2]
            ax.scatter(x,y,z)
            ax.set_xlabel("x")
            ax.set_ylabel("y")
            ax.set_zlabel("z")
            ax.set_title("ArrayPlotter")
            plt.savefig("./2.png")

class TextPlotter(Plotter):
    def __init__(self,path):
        path1="./stopwords_list.txt"
        jieba.load_userdict(path1)#定义停用词词典
        stop=[]
        with open(path1, "r",encoding="utf-8") as f:
            stop=f.readlines()
        self.stop=[i.strip() for i in stop]
        self.path = path
        path_lis=[]
        if isinstance(path,list):#说明传入的是文件列表
            self.path_lis=path
            return
        for root, dirs, names in os.walk(path):#当读入的是文件夹时,则将文件夹力的文本都读入
            for filename in names:
                path_lis.append(os.path.join(root, filename))
        if len(path_lis)==0:#说明读入的不是文件夹
            self.path_lis=[path]
        elif len(path_lis)>0:
            self.path_lis=path_lis

    def plot(self,a):#a表示编号
        text=[]
        for path in self.path_lis:
            with open(path,'r',encoding="utf-8") as f:
                tt=f.readlines()
                tt="".join([i.strip() for i in tt])
                text.append(tt)#将文本都保存在text中
        text=" ".join(text)
        cut=jieba.lcut(text,cut_all=False)
        cut_2=[]
        for wo in cut:
            if wo in self.stop:
                continue
            cut_2.append(wo)
        cut_fre={}
        for item in cut_2:#词频统计
            cut_fre[item]=cut_fre.get(item,0)+1
        items = list(cut_fre.items())  # 由于字典类型没有顺序,将其转化为有顺序的列表类型
        items.sort(key=lambda x: x[1], reverse=True)  # 按照每个列表元素的第二个数,即value进行排序,且为降序
        cut_fre=dict(items[0:50])#选取前50个高频词
        wc=WordCloud(
            width=800,height=600,
            background_color="white",
            font_path='simsun.ttc')
        wc.generate_from_frequencies(cut_fre)
        # 显示词云
        plt.imshow(wc, interpolation='bilinear')
        plt.axis("off")
        wc.to_file(f'./wordcloud{a}.png')
        print('TextPlotter done')

class ImagePlotter(Plotter):
    def __init__(self,path):
        path_lis=[]
        for root, dirs, names in os.walk(path):  # 当读入的是文件夹时,则将文件夹力的文本都读入
            for filename in names:
                path_lis.append(os.path.join(root, filename))
        self.path= path_lis

    def plot(self):
        L=len(self.path)#图片的数量
        n=0
        for i in range(L):
            n=n+1
            if n==4:
                plt.subplot(2,2,4)
                im=Image.open(self.path[i])
                n=0
                plt.imshow(im)
                plt.xticks([])
                plt.yticks([])
                plt.savefig(f"./{math.ceil(i/4)}image.png")
                plt.close()
            else:
                plt.subplot(2,2,n)
                im=Image.open(self.path[i])
                plt.imshow(im)
                plt.xticks([])
                plt.yticks([])
        if L%4==0:
            return
        else:
            plt.savefig(f"./{math.ceil(L/4)}image.png")

class GifPlotter(Plotter):
    def __init__(self,path):
        path_lis = []
        for root, dirs, names in os.walk(path):  # 当读入的是文件夹时,则将文件夹力的文本都读入
            for filename in names:
                path_lis.append(os.path.join(root, filename))
        self.path = path_lis

    def plot(self):
        pic=[]
        for im in self.path:
            io=Image.open(im)
            io=io.resize((300,400))
            pic.append(io)
        imageio.mimsave("./GIF.gif",pic,'gif',duration=0.3, loop=0)

class KeyFeaturePlooter(Plotter):
    def __init__(self,lis):
        #下面对列表做将为操作
        frame = pd.DataFrame(lis)
        pca = PCA(n_components=2)  # 实例化
        pca = pca.fit(frame)  # 拟合模型
        x_dr = pca.transform(frame)  # 获取新矩阵
        point=PointPlotter(x_dr)
        self.pp=point#生成一个实例

    def plot(self):
        self.pp.plot()#调用方法

class MusicPlotter(Plotter):
    #librosa需要配置一个ffmpeg环境
    def __init__(self,path):
        self.path = path

    def plot(self):
        x,sr=librosa.load(self.path)
        librosa.display.waveshow(x, sr=sr)
        plt.savefig('./波形.jpg')

class VideoPlotter(Plotter):
    def __init__(self,path):
        self.path=path
    def plot(self):
        cap = cv2.VideoCapture(self.path)
        gif = []
        count = 1  # 抽帧标志
        while cap.isOpened():
            ret, frame = cap.read()
            if ret == False:
                break
            img = cv2.resize(frame, (int(frame.shape[1] / 4), int(frame.shape[0] / 4)))  # 尺寸缩小为原图的1/4
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # CV BGR转变RGB 否则生成的图片色调有问题
            if count % 7 == 0:  # 每7帧抽1帧
                gif.append(img)
            count += 1
        imageio.mimsave("./video_gif.gif", gif, 'GIF', duration=0.1)

#适配器模式
'''
首先继承父类的初始化结构以及实例
然后将父类的方法名进行统一,这是另一种适配器方法
'''
class PointPlotterAdapter(PointPlotter):
    def __init__(self,pointplotter):
        self.pointplotter=pointplotter

    def plot(self):
        self.pointplotter.plot()

class ArrayPlotterAdapter(ArrayPlotter):
    def __init__(self,arrayplotter):
        self.arrayplotter=arrayplotter

    def plot(self):
        self.arrayplotter.plot()

class TextPlotterAdapter(TextPlotter):
    def __init__(self,textplotter):
        self.textplotter=textplotter

    def plot(self):
        self.textplotter.plot()

class ImagePlotterAdapter(ImagePlotter):
    def __init__(self,imageplotter):
        self.imageplotter=imageplotter

    def plot(self):
        self.imageplotter.plot()

class GifPlotterAdapter(GifPlotter):
    def __init__(self,gifplotter):
        self.gifplotter=gifplotter

    def plot(self):
        self.gifplotter.plot()

class MusicPlotterAdapter(MusicPlotter):
    def __init__(self,musicplotter):
        self.musicplotter=musicplotter

    def plot(self):
        self.musicplotter.plot()

class VideoPlotterAdapter(VideoPlotter):
    def __init__(self,videoplotter):
        self.videoplotter=videoplotter

    def plot(self):
        self.videoplotter.plot()

class KeyFeaturePlooterAdapter(KeyFeaturePlooter):
    def __init__(self,keyfeatureplooter):
        self.keyfeatureplooter=keyfeatureplooter

    def plot(self):
        self.keyfeatureplooter.plot()


def main():
    random.seed()
    '''
    lis_point1=[]
    for i in range(100):
        x=random.randint(1,20)
        y=random.randint(1,20)
        s=(x,y)
        lis_point1.append(s)
    plot1=PointPlotter(lis_point1)
    plot1.plot()



    lis_point2=[]
    x=[random.randint(1,20) for i in range(100)]
    y=[random.randint(1,20) for i in range(100)]
    z=[random.randint(1,20) for i in range(100)]
    lis_point2.append(x)
    lis_point2.append(y)
    lis_point2.append(z)
    plot2=ArrayPlotter(lis_point2)
    plot2.plot()


    #path="./text"#传入一个文件夹
    path2="./text/3.txt"#传入一个文件
    path3=["./text/1.txt","./text/2.txt"]#传入一个文件列表
    plot3=TextPlotter(path)
    plot3.plot(1)
    plot4=TextPlotter(path2)
    plot4.plot(2)
    plot5=TextPlotter(path3)
    plot5.plot(3)


    path4="./images"
    plot6=ImagePlotter(path4)
    plot6.plot()

    path5="./images"
    plot7=GifPlotter(path5)
    plot7.plot()

    path6="./str.mp3"
    plot8=MusicPlotter(path6)
    plot8.plot()

    path7="./父子.mp4"
    plot9=VideoPlotter(path7)
    plot9.plot()

    '''
#以下为适配器的调用方法,通过ohjects提供一个接口
    #objects=[]
    # objects.append(PointPlotterAdapter(plot1))#插入实例
    # objects.append(ArrayPlotterAdapter(plot2))
    # objects.append(TextPlotterAdapter(plot3))
    # objects.append(TextPlotterAdapter(plot4))
    # objects.append(TextPlotterAdapter(plot5))
    # objects.append(ImagePlotterAdapter(plot6))
    # objects.append(GifPlotterAdapter(plot7))
    # objects.append(MusicPlotterAdapter(plot8))
    # objects.append(VideoPlotterAdapter(plot9))
    # #
    # for item in objects:
    #     item.plot()
    x = [random.randint(1, 20) for i in range(100)]
    y = [random.randint(1, 20) for i in range(100)]
    z = [random.randint(1, 20) for i in range(100)]
    d = [random.randint(1, 20) for i in range(100)]
    lis=zip(x,y,z,d)
    plot10=KeyFeaturePlooter(lis)
    plot10.plot()

if __name__=='__main__':
    main()

设计抽象类Plotter

class Plotter(abc.ABC):#构造抽象类Plotter
    @abc.abstractmethod
    def plot(self,*args,**kwargs):
        pass

抽象类为之后类的定义规定了一种方法

数据点型绘制

class PointPlotter(Plotter):
    def __init__(self,lis_point):
        self.point=lis_point
    def plot(self):
        x=[]
        y=[]
        for a,b in self.point:
            x.append(a)
            y.append(b)
        plt.scatter(x,y)
        plt.xlabel("point_x")
        plt.ylabel("point_y")
        plt.title("Draw Point")
        plt.savefig("./1.png")
random.seed()
lis_point1=[]
for i in range(100):
    x=random.randint(1,20)
    y=random.randint(1,20)
    s=(x,y)
    lis_point1.append(s)
plot1=PointPlotter(lis_point1)
plot1.plot()

请添加图片描述

实现多维数组型数组绘制

class ArrayPlotter(Plotter):
    def __init__(self,lis_point):
        self.point=lis_point

    def plot(self):
        if len(self.point)==2:
            x=self.point[0]
            y=self.point[1]
            plt.scatter(x,y)
            plt.xlabel("x")
            plt.ylabel("y")
            plt.title("ArrayPlotter")
            plt.savefig("./2.png")
        elif len(self.point)==3:
            ax=plt.subplot(projection='3d')#创建一个3d工程
            x=self.point[0]
            y=self.point[1]
            z=self.point[2]
            ax.scatter(x,y,z)
            ax.set_xlabel("x")
            ax.set_ylabel("y")
            ax.set_zlabel("z")
            ax.set_title("ArrayPlotter")
            plt.savefig("./2.png")
            

lis_point2=[]
x=[random.randint(1,20) for i in range(100)]
y=[random.randint(1,20) for i in range(100)]
z=[random.randint(1,20) for i in range(100)]
lis_point2.append(x)
lis_point2.append(y)
lis_point2.append(z)
plot2=ArrayPlotter(lis_point2)
plot2.plot()

请添加图片描述

绘制词云

class TextPlotter(Plotter):
    def __init__(self,path):
        path1="./stopwords_list.txt"
        jieba.load_userdict(path1)#定义停用词词典
        stop=[]
        with open(path1, "r",encoding="utf-8") as f:
            stop=f.readlines()
        self.stop=[i.strip() for i in stop]
        self.path = path
        path_lis=[]
        if isinstance(path,list):#说明传入的是文件列表
            self.path_lis=path
            return
        for root, dirs, names in os.walk(path):#当读入的是文件夹时,则将文件夹力的文本都读入
            for filename in names:
                path_lis.append(os.path.join(root, filename))
        if len(path_lis)==0:#说明读入的不是文件夹
            self.path_lis=[path]
        elif len(path_lis)>0:
            self.path_lis=path_lis
    def plot(self,a):#a表示编号
        text=[]
        for path in self.path_lis:
            with open(path,'r',encoding="utf-8") as f:
                tt=f.readlines()
                tt="".join([i.strip() for i in tt])
                text.append(tt)#将文本都保存在text中
        text=" ".join(text)
        cut=jieba.lcut(text,cut_all=False)
        cut_2=[]
        for wo in cut:
            if wo in self.stop:
                continue
            cut_2.append(wo)
        cut_fre={}
        for item in cut_2:#词频统计
            cut_fre[item]=cut_fre.get(item,0)+1
        items = list(cut_fre.items())  # 由于字典类型没有顺序,将其转化为有顺序的列表类型
        items.sort(key=lambda x: x[1], reverse=True)  # 按照每个列表元素的第二个数,即value进行排序,且为降序
        cut_fre=dict(items[0:50])#选取前50个高频词
        wc=WordCloud(
            width=800,height=600,
            background_color="white",
            font_path='simsun.ttc')
        wc.generate_from_frequencies(cut_fre)
        # 显示词云
        plt.imshow(wc, interpolation='bilinear')
        plt.axis("off")
        wc.to_file(f'./wordcloud{a}.png')
        print('TextPlotter done')

path="./text"#传入一个文件夹
path2="./text/3.txt"#传入一个文件
path3=["./text/1.txt","./text/2.txt"]#传入一个文件列表
plot3=TextPlotter(path)
plot3.plot(1)
plot4=TextPlotter(path2)
plot4.plot(2)
plot5=TextPlotter(path3)
plot5.plot(3)            

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

图片布置

class ImagePlotter(Plotter):
    def __init__(self,path):
        path_lis=[]
        for root, dirs, names in os.walk(path):  # 当读入的是文件夹时,则将文件夹力的文本都读入
            for filename in names:
                path_lis.append(os.path.join(root, filename))
        self.path= path_lis

    def plot(self):
        L=len(self.path)#图片的数量
        n=0
        for i in range(L):
            n=n+1
            if n==4:
                plt.subplot(2,2,4)
                im=Image.open(self.path[i])
                n=0
                plt.imshow(im)
                plt.xticks([])
                plt.yticks([])
                plt.savefig(f"./{math.ceil(i/4)}image.png")
                plt.close()
            else:
                plt.subplot(2,2,n)
                im=Image.open(self.path[i])
                plt.imshow(im)
                plt.xticks([])
                plt.yticks([])
        if L%4==0:
            return
        else:
            plt.savefig(f"./{math.ceil(L/4)}image.png")

path4="./images"
plot6=ImagePlotter(path4)
plot6.plot()

以下为一个例子

请添加图片描述

gif动态图

class GifPlotter(Plotter):
    def __init__(self,path):
        path_lis = []
        for root, dirs, names in os.walk(path):  # 当读入的是文件夹时,则将文件夹力的文本都读入
            for filename in names:
                path_lis.append(os.path.join(root, filename))
        self.path = path_lis

    def plot(self):
        pic=[]
        for im in self.path:
            io=Image.open(im)
            io=io.resize((300,400))
            pic.append(io)
        imageio.mimsave("./GIF.gif",pic,'gif',duration=0.3, loop=0)
        
path5="./images"
plot7=GifPlotter(path5)
plot7.plot()        

请添加图片描述

高维数组降维

class KeyFeaturePlooter(Plotter):
    def __init__(self,lis):
        #下面对列表做将为操作
        frame = pd.DataFrame(lis)
        pca = PCA(n_components=2)  # 实例化
        pca = pca.fit(frame)  # 拟合模型
        x_dr = pca.transform(frame)  # 获取新矩阵
        point=PointPlotter(x_dr)
        self.pp=point#生成一个实例

    def plot(self):
        self.pp.plot()#调用方法
        
x = [random.randint(1, 20) for i in range(100)]
y = [random.randint(1, 20) for i in range(100)]
z = [random.randint(1, 20) for i in range(100)]
d = [random.randint(1, 20) for i in range(100)]
lis=zip(x,y,z,d)
plot10=KeyFeaturePlooter(lis)
plot10.plot()        

请添加图片描述

音频图像生成

class MusicPlotter(Plotter):
    #librosa需要配置一个ffmpeg环境
    def __init__(self,path):
        self.path = path

    def plot(self):
        x,sr=librosa.load(self.path)
        librosa.display.waveshow(x, sr=sr)
        plt.savefig('./波形.jpg')
        
path6="./str.mp3"
plot8=MusicPlotter(path6)
plot8.plot()

请添加图片描述

视频截取并生成表情包

class VideoPlotter(Plotter):
    def __init__(self,path):
        self.path=path
    def plot(self):
        cap = cv2.VideoCapture(self.path)
        gif = []
        count = 1  # 抽帧标志
        while cap.isOpened():
            ret, frame = cap.read()
            if ret == False:
                break
            img = cv2.resize(frame, (int(frame.shape[1] / 4), int(frame.shape[0] / 4)))  # 尺寸缩小为原图的1/4
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # CV BGR转变RGB 否则生成的图片色调有问题
            if count % 7 == 0:  # 每7帧抽1帧
                gif.append(img)
            count += 1
        imageio.mimsave("./video_gif.gif", gif, 'GIF', duration=0.1)
        
path7="./父子.mp4"
plot9=VideoPlotter(path7)
plot9.plot()        

请添加图片描述

实现适配器

'''
首先继承父类的初始化结构以及实例
然后将父类的方法名进行统一,这是另一种适配器方法
'''
class PointPlotterAdapter(PointPlotter):
    def __init__(self,pointplotter):
        self.pointplotter=pointplotter

    def plot(self):
        self.pointplotter.plot()

class ArrayPlotterAdapter(ArrayPlotter):
    def __init__(self,arrayplotter):
        self.arrayplotter=arrayplotter

    def plot(self):
        self.arrayplotter.plot()

class TextPlotterAdapter(TextPlotter):
    def __init__(self,textplotter):
        self.textplotter=textplotter

    def plot(self):
        self.textplotter.plot()

class ImagePlotterAdapter(ImagePlotter):
    def __init__(self,imageplotter):
        self.imageplotter=imageplotter

    def plot(self):
        self.imageplotter.plot()

class GifPlotterAdapter(GifPlotter):
    def __init__(self,gifplotter):
        self.gifplotter=gifplotter

    def plot(self):
        self.gifplotter.plot()

class MusicPlotterAdapter(MusicPlotter):
    def __init__(self,musicplotter):
        self.musicplotter=musicplotter

    def plot(self):
        self.musicplotter.plot()

class VideoPlotterAdapter(VideoPlotter):
    def __init__(self,videoplotter):
        self.videoplotter=videoplotter

    def plot(self):
        self.videoplotter.plot()

class KeyFeaturePlooterAdapter(KeyFeaturePlooter):
    def __init__(self,keyfeatureplooter):
        self.keyfeatureplooter=keyfeatureplooter

    def plot(self):
        self.keyfeatureplooter.plot()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值