我写了这段代码,我对相机跟踪对象的代码有疑问,我的问题是{1:我无法理解的主要错误2:在App的屏幕1中添加小部件。请阅读代码。这并不困难 多数民众赞成在单独的代码与不同的观点Kivy build Camera widget
from kivy.lang import Builder
import cv2
import threading
from kivy.uix.widget import Widget
import numpy as np
from kivymd.app import MDApp
from kivy.uix.camera import Camera
from kivymd.theming import ThemeManager
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.uix.list import TwoLineAvatarIconListItem
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from kivy.properties import ObjectProperty
from kivymd.uix.textfield import MDTextField
from kivy.properties import StringProperty
from kivymd.uix.behaviors import (BackgroundColorBehavior,RectangularElevationBehavior,)
from kivymd.uix.button import MDFillRoundFlatButton, MDFillRoundFlatIconButton
from functools import partial
from kivy.app import App
from kivy.uix.image import Image
from kivy.graphics.texture import Texture
# Branch Screen, takes you to S1, S2, or S3
class MyScreenManager(ScreenManager):
pass
class BRANCH(Screen):
pass
class S1(Screen):
pass
class RectangularElevationButton(RectangularElevationBehavior,MDFillRoundFlatIconButton):
md_bg_color = [0, 0, 1, 1]
class TodayScreenElevationButton(RectangularElevationBehavior,MDFillRoundFlatButton):
pass
class RectangularElevationListItem(RectangularElevationBehavior,BackgroundColorBehavior,TwoLineAvatarIconListItem):
md_bg_color = [1, 1, 1, 1]
ROOT=Builder.load_string("""
<RectangularElevationButton>:
size_hint: (0.44, 0.09)
elevation : 8
text_color : rgba('#9370DB')
<TodayScreenElevationButton>:
#size_hint : (0.4, 0.25)
width: dp(100)
height : dp(100)
elevation : 10
md_bg_color : (1, 1, 1, 1)
text_color : rgba('#FFC7B8F5')
<RectangularElevationListItem>:
md_bg_color : (1, 1, 1, 1)
size_hint: (0.9, None)
elevation : 8
MyScreenManager:
BRANCH:
name: 'branch'
S1:
name: 'screen1'
<BRANCH>
FloatLayout:
MDBottomNavigation:
# App.
MDBottomNavigationItem:
name : 'more app'
text : 'More App'
icon : 'open-in-app'
canvas:
Color:
rgba : rgba('#29B473')
RoundedRectangle:
size : self.size
pos : self.pos
Color:
rgba : (1, 1, 1, 1)
RoundedRectangle:
size : self.size[0], self.size[1] - 0.45*self.size[1]
Image :
source: 'icons/download1.png'
size_hint: (0.2, 0.2)
pos_hint : {'center_x' : 0.8, 'center_y' : 0.8}
MDLabel:
text : 'List of TASKs'
font_style : 'H6'
pos_hint : {'x' : 0.06, 'center_y' : 0.855}
size_hint: (0.55, None)
MDIconButton:
icon : 'menu'
size_hint: (None, None)
pos : root.width - 1.5*self.width, root.height - 2.2*self.height
# 1
TodayScreenElevationButton:
pos_hint : {'center_x' : 0.25, 'center_y' : 0.515}
on_release:
root.manager.transition.direction = 'left'
root.manager.current = 'screen1'
Image:
source: 'icons/tracker.png'
size_hint: (0.13, 0.13)
pos_hint: {'center_x' : 0.25, 'center_y' : 0.51}
MDLabel:
text : 'ObjectTracker1'
font_size: '12sp'
size_hint: (0.22, None)
pos_hint: {'x' : 0.20, 'center_y' : 0.40}
# 2
TodayScreenElevationButton:
pos_hint : {'center_x' : 0.75, 'center_y' : 0.515}
Image:
source: 'icons/eyes.png'
size_hint: (0.13, 0.13)
pos_hint: {'center_x' : 0.75, 'center_y' : 0.515}
MDLabel:
text : 'eyes detection'
font_size: '12sp'
size_hint: (0.22, None)
pos_hint: {'x' : 0.69, 'center_y' : 0.40}
# 3
TodayScreenElevationButton:
pos_hint : {'center_x' : 0.25, 'center_y' : 0.24}
Image:
source: 'icons/hale.png'
size_hint: (0.15, 0.15)
pos_hint: {'center_x' : 0.25, 'center_y' : 0.24}
MDLabel:
text : 'color space'
font_size: '12sp'
size_hint: (0.22, None)
pos_hint: {'x' : 0.20, 'center_y' : 0.12}
#4
TodayScreenElevationButton:
pos_hint : {'center_x' : 0.75, 'center_y' : 0.24}
Image:
source: 'icons/frame.png'
size_hint: (0.16, 0.16)
pos_hint: {'center_x' : 0.75, 'center_y' : 0.27}
MDLabel:
text : 'Frame different'
font_size: '12sp'
size_hint: (0.26, None)
pos_hint: {'x' : 0.72, 'center_y' : 0.12}
# Exercise Screen.
MDBottomNavigationItem:
name : 'Find road'
text : 'Find road'
font_size: '4sp'
icon : 'road-variant'
canvas:
Color:
rgba : rgba('#c2c3dc')
RoundedRectangle:
size : self.size
pos : self.pos
Color:
rgba : (1, 1, 1, 1)
RoundedRectangle:
size : self.size[0], self.size[1] - 0.55*self.size[1]
pos : self.pos
Image:
source: 'icons/meditation_bg.png'
#size_hint: (1, 1)
#size_hint_y: 0.4
pos_hint: {'center_x': 0.5, 'center_y' : 0.808}
TodayScreenElevationButton:
pos_hint : {'center_x' : 0.25, 'center_y' : 0.515}
MDRectangleFlatButton:
text: "MDRECTANGLEFLATBUTTON"
text_color: 0, 0, 1, 1
md_bg_color: 1, 1, 0, 1
elevation_normal: 12
pos_hint: {"center_x": .5, "center_y": .5}
MDBottomNavigationItem:
name : 'settings'
text : 'Settings'
icon : 'settings-outline'
<S1>:
id:screen11
FloatLayout:
MDBottomNavigationItem:
name : 'more app'
text : 'More App'
icon : 'open-in-app'
canvas:
Color:
rgba : rgba('#8e80e0')
RoundedRectangle:
size : self.size
pos : self.pos
Color:
rgba : (1, 1, 1, 1)
RoundedRectangle:
size : self.size[0],self.size[1] - 0.2*self.size[1]
Image :
source: 'icons/download1.png'
size_hint: (0.13, 0.13)
pos_hint : {'center_x' : 0.8, 'center_y' : 0.9}
MDLabel:
text : 'c a m e r a'
font_style : 'H6'
pos_hint : {'x' : 0.45, 'center_y' : 0.1}
size_hint: (0.8, None)
TodayScreenElevationButton:
pos_hint : {'center_x' : 0.1, 'center_y' : 0.515}
MDLabel:
text : 'START'
font_size: '20sp'
size_hint: (0.26, None)
pos_hint: {'x' : 0.06, 'center_y' : 0.515}
camera1:
id:vid
<Camera1>:
Image:
size_hint: 0.6, 0.6
allow_stretch: True
keep_ratio: True
pos_hint: {'center_x':0.5, 'top':0.8}
""")
class Camera1(Widget):
def __init__(self, **kwargs):
super(Camera1, self).__init__(**kwargs)
threading.Thread(target=self.doit, daemon=True).start()
def doit(self):
scaling_factor = 0.40
num_frames_to_track = 5
num_frames_jump = 2
tracking_paths = []
frame_index = 0
tracking_params = dict(winSize = (11, 11), maxLevel = 2,
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,
10, 0.03))
# this code is run in a separate thread
self.do_vid = True # flag to stop loop
# make a window for use by cv2
# flags allow resizing without regard to aspect ratio
cv2.namedWindow('Hidden', cv2.WINDOW_NORMAL | cv2.WINDOW_FREERATIO)
# resize the window to (0,0) to make it invisible
cv2.resizeWindow('Hidden', 0, 0)
cam = cv2.VideoCapture(0)
# start processing loop
while (self.do_vid):
ret, frame = cam.read()
frame = cv2.resize(frame, None, fx=scaling_factor,
fy=scaling_factor, interpolation=cv2.INTER_AREA)
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
output_img = frame.copy()
if len(tracking_paths) > 0:
prev_img, current_img = prev_gray, frame_gray
feature_points_0 = np.float32([tp[-1] for tp in \
tracking_paths]).reshape(-1, 1, 2)
feature_points_1, _, _ = cv2.calcOpticalFlowPyrLK(
prev_img, current_img, feature_points_0,
None, **tracking_params)
feature_points_0_rev, _, _ = cv2.calcOpticalFlowPyrLK(
current_img, prev_img, feature_points_1,
None, **tracking_params)
diff_feature_points = abs(feature_points_0 - \
feature_points_0_rev).reshape(-1, 2).max(-1)
good_points = diff_feature_points < 1
new_tracking_paths = []
for tp, (x, y), good_points_flag in zip(tracking_paths,
feature_points_1.reshape(-1, 2), good_points):
if not good_points_flag:
continue
tp.append((x, y))
if len(tp) > num_frames_to_track:
del tp[0]
new_tracking_paths.append(tp)
cv2.circle(output_img, (x, y), 3, (0, 255, 0), -1)
tracking_paths = new_tracking_paths
cv2.polylines(output_img, [np.int32(tp) for tp in \
tracking_paths], False, (0, 150, 0))
if not frame_index % num_frames_jump:
mask = np.zeros_like(frame_gray)
mask[:] = 255
for x, y in [np.int32(tp[-1]) for tp in tracking_paths]:
cv2.circle(mask, (x, y), 6, 0, -1)
feature_points = cv2.goodFeaturesToTrack(frame_gray,
mask = mask, maxCorners = 500, qualityLevel = 0.3,
minDistance = 7, blockSize = 7)
if feature_points is not None:
for x, y in np.float32(feature_points).reshape(-1, 2):
tracking_paths.append([(x, y)])
frame_index += 1
prev_gray = frame_gray
frame=output_img
Clock.schedule_once(partial(self.display_frame, frame))
cv2.imshow('Hidden', frame)
cv2.waitKey(1)
cam.release()
cv2.destroyAllWindows()
def display_frame(self, frame, dt):
texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
texture.blit_buffer(frame.tobytes(order=None), colorfmt='bgr', bufferfmt='ubyte')
texture.flip_vertical()
# actually put the texture in the kivy Image widget
ROOT.ids.screen11.ids.vid.texture = texture
class dastneveshtehApp(MDApp):
def build(self):
obj =ROOT.ids.screen11.ids.vid
obj.add_widget(Camera1())
return ROOT
if __name__ == "__main__":
dastneveshtehApp().run()
这是我的错误
AttributeError Traceback (most recent call last)
<ipython-input-1-85b155ad2927> in <module>
318 obj.add_widget(Camera1())
319 if __name__ == "__main__":
--> 320 dastneveshtehApp().run()
C:\ProgramData\Anaconda3\lib\site-packages\kivy\app.py in run(self)
826 if not self.built:
827 self.load_config()
--> 828 self.load_kv(filename=self.kv_file)
829 root = self.build()
830 if root:
C:\ProgramData\Anaconda3\lib\site-packages\kivy\app.py in load_kv(self, filename)
597 Logger.debug('App: kv <%s> not found' % filename)
598 return False
--> 599 root = Builder.load_file(rfilename)
600 if root:
601 self.root = root
C:\ProgramData\Anaconda3\lib\site-packages\kivy\lang\builder.py in load_file(self, filename, **kwargs)
299 data = data[len(codecs.BOM_UTF8):]
300
--> 301 return self.load_string(data, **kwargs)
302
303 def unload_file(self, filename):
C:\ProgramData\Anaconda3\lib\site-packages\kivy\lang\builder.py in load_string(self, string, **kwargs)
403 self._apply_rule(
404 widget, parser.root, parser.root,
--> 405 rule_children=rule_children)
406
407 for child in rule_children:
C:\ProgramData\Anaconda3\lib\site-packages\kivy\lang\builder.py in _apply_rule(self, widget, rule, rootrule, template_ctx, ignored_consts, rule_children)
655 widget.add_widget(child)
656 child.apply_class_lang_rules(
--> 657 root=rctx['ids']['root'], rule_children=rule_children)
658 self._apply_rule(
659 child, crule, rootrule, rule_children=rule_children)
C:\ProgramData\Anaconda3\lib\site-packages\kivy\uix\widget.py in apply_class_lang_rules(self, root, ignored_consts, rule_children)
467 Builder.apply(
468 self, ignored_consts=ignored_consts,
--> 469 rule_children=rule_children)
470
471 #
C:\ProgramData\Anaconda3\lib\site-packages\kivy\lang\builder.py in apply(self, widget, ignored_consts, rule_children, dispatch_kv_post)
536 self._apply_rule(
537 widget, rule, rule, ignored_consts=ignored_consts,
--> 538 rule_children=rule_children)
539 if dispatch_kv_post:
540 for w in rule_children:
C:\ProgramData\Anaconda3\lib\site-packages\kivy\lang\builder.py in _apply_rule(self, widget, rule, rootrule, template_ctx, ignored_consts, rule_children)
657 root=rctx['ids']['root'], rule_children=rule_children)
658 self._apply_rule(
--> 659 child, crule, rootrule, rule_children=rule_children)
660
661 if rule_children is not None:
C:\ProgramData\Anaconda3\lib\site-packages\kivy\lang\builder.py in _apply_rule(self, widget, rule, rootrule, template_ctx, ignored_consts, rule_children)
657 root=rctx['ids']['root'], rule_children=rule_children)
658 self._apply_rule(
--> 659 child, crule, rootrule, rule_children=rule_children)
660
661 if rule_children is not None:
C:\ProgramData\Anaconda3\lib\site-packages\kivy\lang\builder.py in _apply_rule(self, widget, rule, rootrule, template_ctx, ignored_consts, rule_children)
614 # depending if the child rule is a template or not, we are not
615 # having the same approach
--> 616 cls = Factory_get(cname)
617
618 if Factory_is_template(cname):
C:\ProgramData\Anaconda3\lib\site-packages\kivy\factory.py in __getattr__(self, name)
128 # if trying to access attributes like checking for `bind`
129 # then raise AttributeError
--> 130 raise AttributeError
131 raise FactoryException('Unknown class <%s>' % name)
132
AttributeError:
您的kv
字符串在定义前先使用Camera1
。尝试将class Camera1(Widget)
移到kv
字符串之前。