0
点赞
收藏
分享

微信扫一扫

kivy笔记

女侠展昭 2022-04-06 阅读 36


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


给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()

滚动效果

from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.app import runTouchApp
class ScrollView_layout():
def myself_scrollview(self):
layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
# Make sure the height is such that there is something to scroll.
layout.bind(minimum_height=layout.setter('height'))
for i in range(100):
btn = Button(text=str(i), size_hint_y=None, height=40)
layout.add_widget(btn)
root = ScrollView(do_scroll_x=False,do_scroll_y=True,size_hint=(1, None), size=(Window.width, Window.height))
root.add_widget(layout)
return root
if __name__ == '__main__':
runTouchApp(ScrollView_layout().myself_scrollview())

下拉列表数字版本

class DropDownCoustomNum():

dropdown = DropDown()
@classmethod
def build_10_button(cls,button_num):
for index in range(button_num):
# When adding widgets, we need to specify the height manually
# (disabling the size_hint_y) so the dropdown can calculate
# the area it needs.
btn = Button(text='%d' % index, size_hint_y=None, height=44)
# for each button, attach a callback that will call the select() method
# on the dropdown. We'll pass the text of the button as the data of the
# selection.
btn.bind(on_release=lambda btn:cls.dropdown.select(btn.text))
# then add the button inside the dropdown
cls.dropdown.add_widget(btn)
@classmethod
def build_select_button(cls,button_num):
cls.build_10_button(button_num)
# create a big main button
mainbutton = Button(text='Hello', size_hint=(None, None))
# show the dropdown menu when the main button is released
# note: all the bind() calls pass the instance of the caller (here, the
# mainbutton instance) as the first argument of the callback (here,
# dropdown.open.).
mainbutton.bind(on_release=cls.dropdown.open)
# one last thing, listen for the selection in the dropdown list and
# assign the data to the button text.
cls.dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
return mainbutton

下拉列表字符列表版本

class DropDownCoustomStrList():

dropdown = DropDown()
@classmethod
def build_10_button(cls,button_num):
for index in button_num:
# When adding widgets, we need to specify the height manually
# (disabling the size_hint_y) so the dropdown can calculate
# the area it needs.
btn = Button(text='%s' % index, size_hint_y=None, height=44)
# for each button, attach a callback that will call the select() method
# on the dropdown. We'll pass the text of the button as the data of the
# selection.
btn.bind(on_release=lambda btn:cls.dropdown.select(btn.text))
# then add the button inside the dropdown
cls.dropdown.add_widget(btn)
@classmethod
def build_select_button(cls,button_num):
cls.build_10_button(button_num)
# create a big main button
mainbutton = Button(text='Hello', size_hint=(None, None))
# show the dropdown menu when the main button is released
# note: all the bind() calls pass the instance of the caller (here, the
# mainbutton instance) as the first argument of the callback (here,
# dropdown.open.).
mainbutton.bind(on_release=cls.dropdown.open)
# one last thing, listen for the selection in the dropdown list and
# assign the data to the button text.
cls.dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
return mainbutton

多选框

kivy笔记_ide

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.properties import BooleanProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior

Builder.load_string('''
<SelectableLabel>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
<RV>:
viewclass: 'SelectableLabel'
SelectableRecycleBoxLayout:
default_size: None, dp(56)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
''')


class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleBoxLayout):
''' Adds selection and focus behaviour to the view. '''


class SelectableLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)

def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableLabel, self).refresh_view_attrs(
rv, index, data)

def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)

def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
if is_selected:
print("selection changed to {0}".format(rv.data[index]))
else:
print("selection removed for {0}".format(rv.data[index]))


class RV(RecycleView):
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.data = [{'text': str(x)} for x in range(100)]


class TestApp(App):
def build(self):
return RV()

if __name__ == '__main__':
TestApp().run()

tree样式

kivy笔记_sed_02

from kivy.uix.floatlayout import FloatLayout
from kivy.uix.treeview import TreeView, TreeViewLabel
from kivy.app import runTouchApp

def populate_tree_view(tree_view, parent, node):
if parent is None:
tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
is_open=True))
else:
tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
is_open=True), parent)

for child_node in node['children']:
populate_tree_view(tree_view, tree_node, child_node)


tree = {'node_id': '1',
'children': [{'node_id': '1.1',
'children': [{'node_id': '1.1.1',
'children': [{'node_id': '1.1.1.1',
'children': []}]},
{'node_id': '1.1.2',
'children': []},
{'node_id': '1.1.3',
'children': []}]},
{'node_id': '1.2',
'children': []}]}


class TreeWidget(FloatLayout):
def __init__(self, **kwargs):
super(TreeWidget, self).__init__(**kwargs)

tv = TreeView(root_options=dict(text='Tree One'),
hide_root=False,
indent_level=4)

populate_tree_view(tv, None, tree)

self.add_widget(tv)
if __name__ == '__main__':
runTouchApp(TreeWidget())

选项卡

kivy笔记_kivy_03

'''
TabbedPanel
============

Test of the widget TabbedPanel.
'''

from kivy.app import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.lang import Builder

Builder.load_string("""

<Test>:
size_hint: .5, .5
pos_hint: {'center_x': .5, 'center_y': .5}
do_default_tab: False

TabbedPanelItem:
text: 'first tab'
Label:
text: 'First tab content area'
TabbedPanelItem:
text: 'tab2'
BoxLayout:
Label:
text: 'Second tab content area'
Button:
text: 'Button that does nothing'
TabbedPanelItem:
text: 'tab3'
RstDocument:
text:
'\\n'.join(("Hello world", "-----------",
"You are in the third tab."))

""")


class Test(TabbedPanel):
pass


class TabbedPanelApp(App):
def build(self):
return Test()


if __name__ == '__main__':
TabbedPanelApp().run()

新版本自定相机 使用的时候一定要注意把所有方法和__init__ 放到你要使用的类中

class CustomCamera():
def __init__(self):
self.Flag_list = [0, 1]
self.image_from_camera = []
self.camera_flog = [False]
self.detail_flog = [False]

# 将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 = self.Flag_list[0].read()
if ret:
node1 = self.numpy_to_texture(frame[:, ::-1, :])
self.image_from_camera.append(node1)
self.camera_to_page()

# 这就是动态显示的模板
def camera_to_page(self):
# 显示相机到页面
if len(self.image_from_camera) >=1:
print("的点点滴滴多多多多多多多多多多")
node1 = self.image_from_camera.pop(0)
self.Flag_list[1].clear_widgets()
if self.camera_flog:
node = Scatter(pos=self.Flag_list[1].pos, size=self.Flag_list[1].size)
with node.canvas:
Rectangle(size=node.size, texture=node1)
self.Flag_list[1].add_widget(node)
# self.Flag_list[0].add_widget(node2)

# 自定义相机
def coustom_camera(self, par):
self.Flag_list[1] = par
self.camera_flog[0] = not self.camera_flog[0]
if not self.camera_flog[0]:
self.Flag_list[0].release()
self.image_from_camera = []
print("tun off")
try:
cap = cv2.VideoCapture(0)
except:
cap = cv2.VideoCapture(1)
self.Flag_list[0] = cap
if not self.camera_flog[0]:
cap.release()
Clock.unschedule(self.cam)
else:
Clock.schedule_interval(self.cam, 1.0 / 20)

使用这样的方式调用可以实现人脸识别特效

'./face_boder.png’前提是该图有一定的部分是透明的

GridLayout:
size_hint_y: None
height:300
size_hint_x: None
width:300
cols:1
AnchorLayout:

Button:
on_release:app.root.FaceLoginScreen_index.coustom_camera(self)
Image:
source: './face_boder.png'
size: self.texture_size



举报

相关推荐

0 条评论