kivy笔记

from kivy.uix.image import Image
Image(source="x.jpg").texture.pixels==open("x.jpg","rb").read()
获得一个图片的二进制数据
kv语言模板
https://my.oschina.net/olddragon/blog/791374
kivy做的本地聊天软件
https://github.com/yingshaoxo/kivy-chat

kv屏幕切换

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
class MainScreen(Screen):
    pass

class AnotherScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

presentation = Builder.load_file("main.kv")

class MainApp(App):
    def build(self):
        return presentation

if __name__ == '__main__':
    MainApp().run()
#:kivy 1.8.0
#:import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
    transition: FadeTransition()
    MainScreen:
    AnotherScreen:

<MainScreen>:
    name: 'main'

    Button:
        on_release: app.root.current = 'other'
        text: 'Another Screen'
        font_size: 50

<AnotherScreen>:
    name: 'other'

    Button:
        on_release: app.root.current = 'main'
        text: 'back to the home screen'
        font_size: 50

原址:https://pythonprogramming.net/kivy-screen-manager-tutorial/

给layout加图片

<MainScreen>:
    name: 'main'
    Button:
        on_release: app.root.current = 'other'
        text: 'hello world'
        font_size: 50
    AsyncImage:
        source: '/home/chenyang/PycharmProjects/show_face_decetor/logo.jpg'
    
从matpoltlib中拿出图片
https://blog.csdn.net/C_chuxin/article/details/84000438


import matplotlib.pyplot as plt
 
import numpy as np
 
import io
 
from PIL import Image
 
import cv2
 
 
 
#使用plt进行画图
 
img = Image.open('00.jpg') #读取图片像素为512X512
 
fig=plt.figure("Image",frameon=False)  # 图像窗口名称
 
plt.imshow(img)
 
canvas = fig.canvas
 
 
 
# 去掉图片四周的空白
 
plt.axis('off') # 关掉坐标轴为 off
 
#设置画布大小(单位为英寸),每1英寸有100个像素
 
fig.set_size_inches(512/100,512/100)
 
plt.gca().xaxis.set_major_locator(plt.NullLocator())  # plt.gca()表示获取当前子图"Get Current Axes"。
 
plt.gca().yaxis.set_major_locator(plt.NullLocator())
 
plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
 
plt.margins(0, 0)
 
 
 
#第一种保存方式(直接对plt 进行保存)
 
plt.savefig('01.jpg',dpi=100)
 
 
 
# 第二种保存方式(获取Plt的数据并使用cv2进行保存)
 
buffer = io.BytesIO()  # 获取输入输出流对象
 
canvas.print_png(buffer)  # 将画布上的内容打印到输入输出流对象
 
data = buffer.getvalue()  # 获取流的值
 
print("plt的二进制流为:\n",data)
 
buffer.write(data)  # 将数据写入buffer
 
img = Image.open(buffer)  # 使用Image打开图片数据
 
img = np.asarray(img)
 
print("转换的图片array的尺寸为:\n",img.shape)
 
print("转换的图片array为:\n",img)
 
cv2.imwrite("02.jpg", img)
 
buffer.close()

 # 将Texture格式的图片对象转换为numpy
    def texture_to_numpy(self,data):
        image=numpy.asarray(bytearray(data.pixels), dtype='uint8').reshape((data.height,data.width,4))
        r_chanel=numpy.copy(image[:,:,0])
        g_chanel=numpy.copy(image[:,:,1])
        b_chanel=numpy.copy(image[:,:,2])
        image[:, :, 0]=b_chanel
        image[:, :, 1]=g_chanel
        image[:, :, 2]=r_chanel
# 将numpy格式图片对象转为Texture 
    def numpy_to_texture(self,frame):
        # frame=cv2.imread("ddd.jpg")
        buf1 = cv2.flip(frame, 0)
        buf = buf1.tostring()
        image_texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
        image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
class ImageToImage:
    def pie_plt(self):
        # -*- coding: utf-8 -*

        from matplotlib.font_manager import FontManager, FontProperties
        import matplotlib as mpl
        import matplotlib.pyplot as plt

        # 使用Mac系统自带的中问字体
        def getChineseFont():
            return FontProperties(fname='/System/Library/Fonts/STHeiti Medium.ttc')

        # 设置图片大小
        # plt.figure(figsize=(9,6))
        label = u'超载', u'船员责任心不强', u'船员驾驶技术太差', u'通航环境差', u'海事、港航监管不到位', u'船舶过于老旧', u'冒险航行'  # 各类别标签
        color = 'red', 'orange', 'yellow', 'green', 'blue', 'gray', 'goldenrod'  # 各类别颜色
        size = [34, 5, 6, 14, 1, 10, 23]  # 各类别占比
        explode = (0.2, 0, 0, 0, 0, 0, 0)  # 各类别的偏移半径

        # plt.subplot(2,3,1)
        # 绘制饼状图
        pie = plt.pie(size, colors=color, explode=explode, labels=label, shadow=True, autopct='%1.1f%%')
        # 饼状图呈正圆
        for font in pie[1]:
            font.set_fontproperties(mpl.font_manager.FontProperties(
                fname='/System/Library/Fonts/STHeiti Light.ttc'))
            font.set_size(8)
        for digit in pie[2]:
            digit.set_size(8)

        plt.axis('equal')
        plt.title(u'你认为砂石船发生事故的主要原因在于', fontproperties=getChineseFont(), fontsize=12)

        plt.legend(prop=getChineseFont(), loc=0, bbox_to_anchor=(0.82, 1))  # 图例
        # 设置legend的字体大小
        leg = plt.gca().get_legend()
        ltext = leg.get_texts()
        plt.setp(ltext, fontsize=6)
        # 显示图
        plt.show()
    def plt_image(self,num_list,imagename):
        fig = plt.figure(imagename, frameon=False,figsize=(5.2,2.7))# 图像窗口名称
        self.canvas = fig.canvas
        name_list = ['Surprise', "Fear", "Disgust", "Happy", "Sad", "Anger", "Nature"]
        # num_list = [round(random.random() * 100, 2), round(random.random() * 100, 2), round(random.random() * 100, 2),
        #             round(random.random() * 100, 2), round(random.random() * 100, 2), round(random.random() * 100, 2),
        #             round(random.random() * 100, 2)]
        rects = plt.bar(range(len(num_list)), num_list, color='rgbyrgb')
        index = [0, 1, 2, 3, 4, 5, 6]
        index = [float(c) for c in index]
        plt.ylim(ymax=110, ymin=0)
        plt.xticks(index, name_list)
        plt.ylabel("arrucay(%)") # X轴标签
        ax = plt.gca()
        ax.spines['top'].set_color('none')
        ax.spines['right'].set_color('none')
        for rect in rects:
            height = round(rect.get_height(),2)
            if height<1:
                plt.text(rect.get_x() + rect.get_width() / 2, height,' ', ha='center', va='bottom')
            else:
                plt.text(rect.get_x() + rect.get_width() / 2, height, str(height) + '%', ha='center', va='bottom')
        # plt.cla()
        plt.close("all")
拍照截屏
https://stackoverflow.com/questions/54551968/python-kivy-camera-and-changing-screen

https://stackoverflow.com/questions/35718277/kivycameraubuntu-error-with-v4l2src

Kivy 从memory 读取image

https://www.cnblogs.com/jeroen/p/9236549.html

kivy 基础: widget, texture的使用

https://www.jianshu.com/p/e0be47e27b30
#采取全局变量传递当前layout控制布局
current_layout=[]
# 被重构的Camera类
class Puzzle(Camera):

    #写一个方法设置布局对象到这个类的变量中

    def on_texture_size(self, instance, value):
        self.dector_expression = Dector_Expression()
        self.new_build()

    def on_blocksize(self, instance, value):
        self.new_build()
    # 基础build
    def build(self):
        self.clear_widgets()
        texture = self.texture
        subtexture = texture
        node = Scatter(pos=(320, 240), size=(640, 480))
        with node.canvas:
            Color(1, 1, 1)
            Rectangle(size=node.size, texture=subtexture)
        self.add_widget(node)
    # 重构build
    def new_build(self):
        self.clear_widgets()
        texture = self.texture
        subtexture = texture
        node = Scatter( size=(640, 480), size_hint=(0.5 ,0.5)
        ,pos_hint={'center_x':0.5, 'center_y':0.5})
        with node.canvas:
            Color(1, 1, 1)
            Rectangle(size=node.size, texture=subtexture)
        print(current_layout)
        current_layout[0].add_widget(node)
#通过button传递当前layout对象到.py文件中
Button:
                on_release:app.root.clock_image(self)
                text:'打开摄像头'
                font_size: 50
#
class ScreenManagement(ScreenManager):
	def clock_image(self, app):
		#传递layout到变量中
	        current_layout.append(app.parent.parent.children[2])
	        puzzle = Puzzle(resolution=(40, 80), play=True)
	        app.parent.parent.children[1].add_widget(puzzle)
	        #将相机layout对象传递出去
	        self.camera_layout = app.parent.parent.parent.children[1].children[0]
	        
# 自定义button
class ImageButton(ButtonBehavior,FloatLayout, Image):
    def on_press(self):
        print ('pressed')
#自定义button的使用
ImageButton:
                on_release: app.root.login(self)
                text: '登录'
                font_size: 50
                source: './logo5.png'
#相机贴图
def new_build(self, *kwargs):
    self.clear_widgets()
    node = ImageButton(source='imagecamera.png', size=self.size, pos=self.pos)
    self.add_widget(node)
 def cam(self, *kwargs):
        Flag_list[0].clear_widgets()
        node = ImageButton(source='imagecamera.png', size=self.size, pos=self.pos)
        node1 = ImageButton(source='test.png', size=self.size, pos=self.pos)
        if random.randrange(2) == 0:
            Flag_list[0].add_widget(node)
        else:
            Flag_list[0].add_widget(node1)
     
camera = self.camera_layout
par=camera.parent
Flag_list.append(par)
Clock.schedule_interval(self.cam, 1.0 / 5)
# 将numpy转为texture
    def numpy_to_texture(self, frame, colorfmt='bgr'):
        buf1 = cv2.flip(frame, 0)
        buf = buf1.tostring()
        image_texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt=colorfmt)
        image_texture.blit_buffer(buf, colorfmt=colorfmt, bufferfmt='ubyte')
        return image_texture

    def cam(self,*kwargs):

        ret,frame=Flag_list[1].read()
        if ret:
            node1=self.numpy_to_texture(frame)
        else:
            return
        Flag_list[0].clear_widgets()
        node = Scatter(pos=Flag_list[0].pos, size=Flag_list[0].size)
        with node.canvas:
            Rectangle(size=node.size, texture=node1)

        Flag_list[0].add_widget(node)
    def coustom_camera(self,par):
        Flag_list.append(par.parent.parent.parent.children[1])
        # 开始的时候要加一个图片
        node = ImageButton(source='imagecamera.png', size=self.size, pos=self.pos)
        Flag_list[0].add_widget(node)
        cap = cv2.VideoCapture(0)
        Flag_list.append(cap)
        Clock.schedule_interval(self.cam, 1.0 / 5)
自定义字体
import numpy as np
import pylab as pl
import matplotlib.font_manager as fm
myfont = fm.FontProperties(fname=r'D:\Fonts\simkai.ttf') # 设置字体
t = np.arange(0.0,2.0 * np.pi,0.01) # 自变量取值范围
s = np.sin(t) # 计算正弦函数值
z = np.cos(t) # 计算余弦函数值
pl.plot(t,s,label='正弦')
pl.plot(t,z,label='余弦')
pl.xlabel('x-变量',fontproperties=myfont,fontsize=24) #设置标签
pl.ylabel('y-正弦余弦函数值',fontproperties=myfont,fontsize=24)
pl.title('sin-cos函数图像',fontproperties=myfont,fontsize=32) #图像标题
pl.legend(prop=myfont)
pl.show()
发布了172 篇原创文章 · 获赞 52 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_32759777/article/details/103468822