Procházet zdrojové kódy

cleanup: Vopen->PixelMedia self.cv2->cv2 img_draw...

micha před 4 dny
rodič
revize
e0b4feff23
1 změnil soubory, kde provedl 155 přidání a 129 odebrání
  1. 155 129
      vpu/vpu_live4.py

+ 155 - 129
vpu/vpu_live4.py

@@ -99,6 +99,8 @@ def select_ip(ips, univ=2): # artnet univ
         if "ltp-out" in ip and _univ in ip:
             return ip
 
+INPUT_START_POS_X = 40
+INPUT_START_POS_Y = 236 #320
 
 FUNC = 0
 COUNTER = []
@@ -149,9 +151,9 @@ def read_dmx(ip):
 
 # ===== ARTNET DMX =========
 
-PLAYLIST = []
+MEDIALIST = []
 try:
-    PLAYLIST = open_playlist()
+    MEDIALIST = open_medialist()
 except:pass
 
 #import json
@@ -160,10 +162,55 @@ except:pass
 sys.path.insert(0,"/opt/LibreLight/Xdesk/")
 from tool.video_capture import scan_capture #as scan_capture
 
-class Vopen():
+def _cam_cfg_new(fn):
+    #fn = HOME+'/LibreLight/video_in.txt'
+    txt = [
+        "# Example",
+        "d0 w640 h480 # PAL",
+        "d0 w800 h600 # SVGA",
+        "d0 w960 h540 # 540p",
+        "d0 w1024 h768 # XGA <---",
+        "d0 w1280 h720 # 720p",
+        "d0 w1440 h900  # WSXGA+",
+        "d0 w1600 h900  # WSXGA - Laptop 16:9",
+        "d0 w1920 h1080 # HD 1080p",
+        "",
+        "# config",
+        "d0 w1024 h768 # XGA",
+    ]
+    f = open(fn ,"w")
+    f.write("\n".join(txt))
+    f.close()
+
+def _cam_cfg():
+    fn = HOME+'/LibreLight/video_in.txt'
+    if not os.path.isfile(fn):
+        _cam_cfg_new(fn)
+    f = open(fn ,"r")
+    lines = f.readlines()
+    f.close()
+    cfg = ""
+    for i in lines:
+        if i.startswith("d"):
+            cfg = i
+    cfg = cfg.split()
+    capture = scan_capture(name="MiraBox",serial="")
+    if capture:
+        print("capture",capture)
+        try:
+            cfg.append(capture[0][0])
+        except Exception as e:
+            print("except 2992",e)
+    else:
+        print("---- ERROR NO VIDEO CAPTURE DEV - FOUND ----")
+    print("_cam_cfg:",len(cfg),[cfg])
+    
+    return cfg
+
+class PixelMedia():
 
     def __init__(self,dmx=None,_id=None):
-        global PLAYLIST
+        global MEDIALIST
 
         self._id = _id
         self.fpath = HOME+'/Downloads/'
@@ -171,9 +218,9 @@ class Vopen():
         self.fname = '' #'bbb_sunflower_480x320.mp4'
         #self.fname = 'no-video.mp4'
         try:
-            self.fname = PLAYLIST[0]
+            self.fname = MEDIALIST[0]
         except Exception as e:
-            print("Exception set video from PLAYLIST 5543:",e)
+            print("Exception set video from MEDIALIST 5543:",e)
         
         self.restart_t = time.time()
         self.fps = 0
@@ -190,7 +237,6 @@ class Vopen():
         self.shape = [200,200]  
         self.img = None
         self.success = 1
-        self.cv2 = None
         self._run = 0
         self.end = 0
         self._video_nr = 0
@@ -199,11 +245,6 @@ class Vopen():
 
         self.shape_x = 370
         self.shape_y = 235
-        try:
-            global cv2
-            self.cv2 = cv2
-        except:
-            pass
 
         self.init()
 
@@ -219,8 +260,8 @@ class Vopen():
         self.restart_t = time.time()
 
     def init(self):
-        print("---- ---- Vopen.init()",[self.fname,self._video_nr])
-        print(PLAYLIST)
+        print("---- ---- PixelMedia.init()",[self.fname,self._video_nr])
+        print(MEDIALIST)
         self.time = 0
         self.t_delta = 0 
         self.t_last  = time.time()
@@ -240,64 +281,21 @@ class Vopen():
                 if self._video_nr >= 25:
                     self.fname = "cam_"
                     self.init()
-                elif self._video_nr < len(PLAYLIST):
-                    self.fname = str(PLAYLIST[self._video_nr])
+                elif self._video_nr < len(MEDIALIST):
+                    self.fname = str(MEDIALIST[self._video_nr])
                     self.init()
 
         except Exception as e:
-            print("Vopen.select_video()",dmx_value,e)
+            print("PixelMedia.select_video()",dmx_value,e)
 
     def close_cap():
-        print(dir(self.Rcap)) # = self.cv2.VideoCapture(self.fpath+self.fname)
-
-    def _cam_cfg_new(self,fn):
-        #fn = HOME+'/LibreLight/video_in.txt'
-        txt = [
-            "# Example",
-            "d0 w640 h480 # PAL",
-            "d0 w800 h600 # SVGA",
-            "d0 w960 h540 # 540p",
-            "d0 w1024 h768 # XGA <---",
-            "d0 w1280 h720 # 720p",
-            "d0 w1440 h900  # WSXGA+",
-            "d0 w1600 h900  # WSXGA - Laptop 16:9",
-            "d0 w1920 h1080 # HD 1080p",
-            "",
-            "# config",
-            "d0 w1024 h768 # XGA",
-        ]
-        f = open(fn ,"w")
-        f.write("\n".join(txt))
-        f.close()
+        print(dir(self.Rcap)) # = cv2.VideoCapture(self.fpath+self.fname)
+
     
-    def _cam_cfg(self):
-        fn = HOME+'/LibreLight/video_in.txt'
-        if not os.path.isfile(fn):
-            self._cam_cfg_new(fn)
-        f = open(fn ,"r")
-        lines = f.readlines()
-        f.close()
-        cfg = ""
-        for i in lines:
-            if i.startswith("d"):
-                cfg = i
-        cfg = cfg.split()
-        capture = scan_capture(name="MiraBox",serial="")
-        if capture:
-            print("capture",capture)
-            try:
-                cfg.append(capture[0][0])
-            except Exception as e:
-                print("except 2992",e)
-        else:
-            print("---- ERROR NO VIDEO CAPTURE DEV - FOUND ----")
-        print("_cam_cfg:",len(cfg),[cfg])
-        
-        return cfg
 
     def _open_cam(self):
         # LIVE VIDEO INPUT UVC DEVICE
-        cfg = self._cam_cfg()
+        cfg = _cam_cfg()
 
 
         res = "HD"
@@ -336,9 +334,9 @@ class Vopen():
         if self._stop:
             df += "_stop"
         elif os.path.exists("/dev/{}".format(df)):
-            self.Rcap = self.cv2.VideoCapture(d)
-            self.Rcap.set(self.cv2.CAP_PROP_FRAME_WIDTH, w)
-            self.Rcap.set(self.cv2.CAP_PROP_FRAME_HEIGHT, h)
+            self.Rcap = cv2.VideoCapture(d)
+            self.Rcap.set(cv2.CAP_PROP_FRAME_WIDTH, w)
+            self.Rcap.set(cv2.CAP_PROP_FRAME_HEIGHT, h)
         else:
             #self.Rcap = None
             #self.end = 1
@@ -359,14 +357,14 @@ class Vopen():
             #exit()
     
         self.Rsuccess = 0
-        if self.cv2:
+        if cv2:
             if self._stop:
                 return
 
             if self.fname.startswith("cam_"): 
                 self._open_cam()
             else:
-                self.Rcap = self.cv2.VideoCapture(self.fpath+self.fname, cv2.CAP_FFMPEG) 
+                self.Rcap = cv2.VideoCapture(self.fpath+self.fname, cv2.CAP_FFMPEG) 
                 #FFMPEG malloc(): unsorted double linked list corrupted ... Abgebrochen
 
             print("_init ?",self.Rcap)
@@ -414,7 +412,7 @@ class Vopen():
                 if self.fps == 0:
                     self.fps = cap.get(cv2.CAP_PROP_FPS)
                 
-                img = self.cv2.cvtColor(img, self.cv2.COLOR_BGR2RGB)
+                img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
                 if self.fname.startswith("cam_"): 
                     pass
                     #img = self.rescale_frame2(img, 1200)
@@ -494,8 +492,8 @@ class Vopen():
             image = self.moveImage(image,x=delta_x,y=delta_y,shape=bg_shape)
 
             bg_shape = tuple(bg_shape) # exception ... if angle 0 no tuple !!!
-            rot_mat = self.cv2.getRotationMatrix2D(center,angle,1.0) 
-            frame   = self.cv2.warpAffine(image, rot_mat,  bg_shape  ) #,flags=self.cv2.INTER_LINEAR)
+            rot_mat = cv2.getRotationMatrix2D(center,angle,1.0) 
+            frame   = cv2.warpAffine(image, rot_mat,  bg_shape  ) #,flags=cv2.INTER_LINEAR)
             return frame
         except Exception as e:
             raise(e)
@@ -509,20 +507,20 @@ class Vopen():
         else:
             num_cols,num_rows = shape #[1::-1]
         # Image translation
-        frame = self.cv2.warpAffine(img, translation_matrix, (num_cols,num_rows))
+        frame = cv2.warpAffine(img, translation_matrix, (num_cols,num_rows))
         return frame
 
     def rescale_frame2(self,frame, width):
         height = int(frame.shape[0]/frame.shape[1] * width )
         dim = (width, height)
-        #return self.cv2.resize(frame, dim, interpolation =cv2.INTER_AREA)
-        return self.cv2.resize(frame, dim, interpolation =cv2.INTER_LINEAR)
+        #return cv2.resize(frame, dim, interpolation =cv2.INTER_AREA)
+        return cv2.resize(frame, dim, interpolation =cv2.INTER_LINEAR)
 
     def rescale_frame(self,frame, percent=75):
         width  = int(frame.shape[1] * percent/ 100)
         height = int(frame.shape[0] * percent/ 100)
         dim = (width, height)
-        return self.cv2.resize(frame, dim, interpolation =cv2.INTER_LINEAR)
+        return cv2.resize(frame, dim, interpolation =cv2.INTER_LINEAR)
 
     def pause(self):
         #print("pause",self.t_last)
@@ -555,7 +553,11 @@ class Vopen():
         if self.buffer:
             self._img = self.buffer[int(self.pos)]
             self.img = self._img
-
+    def check_cv2_check(self):
+        if not cv2:
+            cprint("cv2 not importet ! no VIDEO support !",color="red")
+            return 0
+        return 1
     def next(self):
          
         try:
@@ -574,7 +576,7 @@ class Vopen():
                 print("next",_id)
 
             # add DIMER to videplayer
-            self.cv2.normalize(self.img, self.img, 0, self.dim, self.cv2.NORM_MINMAX) 
+            cv2.normalize(self.img, self.img, 0, self.dim, cv2.NORM_MINMAX) 
             
             img = self.img 
             if img is None:
@@ -712,7 +714,7 @@ class Vopen():
         fr = font15.render("{}".format(self.fname) ,1, (0,0,0))
         wn.blit(fr,(70,MAIN_SIZE[1]-(self._id+1)*35+15))
 
-Vopen = Vopen
+PixelMedia = PixelMedia
 
 VIDEO = []
 videoplayer=[]            
@@ -740,7 +742,7 @@ if type(options.videoplayer) is str:
         print("-- videoplayer dmx:",cdmx)
         try:
             cdmx = int(cdmx)
-            videoplayer.append( Vopen(cdmx,_id=_vid) )
+            videoplayer.append( PixelMedia(cdmx,_id=_vid) )
             _vid += 1
             _tmp = {"DMX":cdmx,"DIM":0,"PAN":127,"TILT":127
                     ,"CONTROL":0,"SEC":10,"VIDEO":"3"
@@ -757,7 +759,7 @@ def loop_videoplayer():
         _videoplayer = videoplayer[:]
         #print(".")
         ok = 0
-        for i in _videoplayer: #.append( Vopen(cdmx,_id=_vid) )
+        for i in _videoplayer: #.append( PixelMedia(cdmx,_id=_vid) )
             try:
                 r = i._read() # read next frame from file
                 if r:
@@ -773,19 +775,19 @@ def loop_videoplayer():
 thread.start_new_thread(loop_videoplayer,())
 # ===== ======
 
-#self.fname = PLAYLIST[0]
+#self.fname = MEDIALIST[0]
 videoplayer2 = []
 def loop2_videoplayer():
     while 1:
         print()
         print()
         print()
-        for i,v in enumerate(PLAYLIST):
+        for i,v in enumerate(MEDIALIST):
             try:
                 video1 = videoplayer2[i] 
                 video1.select_video(i)
             except:
-                vi = Vopen(181,1) 
+                vi = PixelMedia(181,1) 
                 videoplayer2.append( vi )
 
 
@@ -793,7 +795,7 @@ def loop2_videoplayer():
 
         ok = 0
         j =0 
-        for i in _videoplayer: #.append( Vopen(cdmx,_id=_vid) )
+        for i in _videoplayer: #.append( PixelMedia(cdmx,_id=_vid) )
             try:
                 r = i._read() # read next frame from file
                 if r:
@@ -925,8 +927,8 @@ vpu_wall_conf_file = HOME+"/LibreLight/vpu_wall_conf.csv"
 
 grid_file = "/tmp/vpu_grid_hd.csv"
 text_file = HOME+"/LibreLight/vpu_text_hd.csv"
-play_list = "/tmp/vpu_playlist_hd.csv"
-play_list = HOME+"/LibreLight/video/" #.format(path)
+media_list = "/tmp/vpu_medialist_hd.csv"
+media_list = HOME+"/LibreLight/video/" #.format(path)
 pm_wy = 0
 if options.pixel_mapping:
     PIXEL_MAPPING = 1
@@ -937,8 +939,8 @@ if options.pixel_mapping:
     if options.dual_vpu:
         grid_file = HOME+"/LibreLight/vpu_grid_dual{}.csv".format(path)
     text_file = HOME+"/LibreLight/vpu_text_hd{}.csv".format(path)
-    play_list = HOME+"/LibreLight/vpu_playlist_hd{}.csv".format(path)
-    play_list = HOME+"/LibreLight/video/" #.format(path)
+    media_list = HOME+"/LibreLight/vpu_medialist_hd{}.csv".format(path)
+    media_list = HOME+"/LibreLight/video/" #.format(path)
     #_x = 8
     #_y = 8
 
@@ -960,7 +962,7 @@ try:
     wy = 40+40+block[1] * _y 
 
     if type(options.videoplayer) is str:
-        wy += 150 # video playlist
+        wy += 150 # video medialist
 
     MAIN_SIZE=(wx,wy)
 
@@ -1232,11 +1234,9 @@ class POINTER():
         window.blit(fr,(10,40))
 
         if 1: #self._x > 30 and self._y > 230:
-            #from_x_min = 40 #320
-            #from_y_min = 236
             # pointer
-            _x = self._x-40
-            _y = self._y-236
+            _x = self._x-INPUT_START_POS_X
+            _y = self._y-INPUT_START_POS_Y
             rgb = [200,200,200]
             if _x < 0:
                 rgb = [200,0,0]
@@ -1378,23 +1378,23 @@ def draw_overlay():
     #fr = font15.render("ip:{}".format(IP) ,1, (200,0,255))
     #window.blit(fr,(100,2))
 
-    fr = font15.render("start-uni: {:}.xx dRGB".format(options.start_univ) ,1, (200,0,255))
+    fr = font15.render("start-uni: {:}.xx dRGB".format(START_UNIV) ,1, (200,0,255))
     window.blit(fr,(90,2))
 
-    fr = font15.render("a1_idim: 1.{:}".format(options.grid_a1_idim) ,1, (200,0,255))
+    fr = font15.render("a1_idim: {}.{:}".format(START_UNIV_A,options.grid_a1_idim) ,1, (200,0,255))
     window.blit(fr,(90,12))
 
-    fr = font15.render("a2_idim: 1.{:}".format(options.grid_a2_idim) ,1, (200,0,255))
+    fr = font15.render("a2_idim: {}.{:}".format(START_UNIV_A,options.grid_a2_idim) ,1, (200,0,255))
     window.blit(fr,(90,22))
 
-    fr = font15.render("gobo_ch1: 1.{:}".format(options.gobo_ch) ,1, (200,0,255))
+    fr = font15.render("gobo_ch1: {}.{:}".format(START_UNIV_A,options.gobo_ch) ,1, (200,0,255))
     window.blit(fr,(180,12))
-    fr = font15.render("gobo_ch2: 1.{:}".format(options.gobo_ch2) ,1, (200,0,255))
+    fr = font15.render("gobo_ch2: {}.{:}".format(START_UNIV_A,options.gobo_ch2) ,1, (200,0,255))
     window.blit(fr,(180,22))
 
-    fr = font15.render("v-play1: 1.{:}".format(vplay1) ,1, (200,0,255))
+    fr = font15.render("v-play1: {}.{:}".format(START_UNIV_A,vplay1) ,1, (200,0,255))
     window.blit(fr,(270,12))
-    fr = font15.render("v-play2: 1.{:}".format(vplay2) ,1, (200,0,255))
+    fr = font15.render("v-play2: {}.{:}".format(START_UNIV_A,vplay2) ,1, (200,0,255))
     window.blit(fr,(270,22))
 
     try:
@@ -1484,18 +1484,18 @@ def open_text_block():
 TEXT_BLOCK = open_text_block()
 TEXT_BLOCK_TIME = time.time()
 
-# video playlist 
+# video medialist 
 
-PLAYLIST = []
+MEDIALIST = []
 
 
-def open_playlist():
-    print("======== OPEN PLAYLIST DIR !!",play_list)
+def open_medialist():
+    print("======== OPEN MEDIALIST DIR !!",media_list)
 
-    if not os.path.isdir(play_list):
-        os.system("mkdir -p {}".format(play_list))
+    if not os.path.isdir(media_list):
+        os.system("mkdir -p {}".format(media_list))
 
-    _lines = os.listdir(play_list)
+    _lines = os.listdir(media_list)
     _lines.sort()
 
     lines = ['']*25 
@@ -1515,8 +1515,8 @@ def open_playlist():
             lines.append("")#"LINE ERROR")
     return lines
 
-PLAYLIST_TIME = time.time()
-PLAYLIST = open_playlist()
+MEDIALIST_TIME = time.time()
+MEDIALIST = open_medialist()
 # ===== GUI =========
 
 
@@ -1628,6 +1628,7 @@ GRID = []
 GRID_A = []
 
 NR = 0
+START_UNIV_A=1
 START_UNIV=2
 if options.start_univ:
     try:
@@ -1779,8 +1780,8 @@ read_wall_pix(init=1)
 def reshape2(GRID,GRID_OUT,_x,_y,name="GRID_Z"): 
     _w = 16
     _h = 16
-    from_x_min = 40 #320
-    from_y_min = 236
+    from_x_min = INPUT_START_POS_X 
+    from_y_min = INPUT_START_POS_Y
 
     target_x = 40 # min
     target_y = 60 # min
@@ -2099,7 +2100,7 @@ def draw_video(VIDEO):
                 _cdmx = video1.dmx
                 del_video1 = video1
 
-                video1 = Vopen(cdmx,_id=_vid) 
+                video1 = PixelMedia(cdmx,_id=_vid) 
                 video1.select_video(count[k])
                 videoplayer[i] = video1
 
@@ -2500,7 +2501,7 @@ def draw_output_label(CFG,value,dmx="0.0",name="GRID_XX"):
     fr_r = fr.get_rect(center=(int(wx/2),int(0+pm_wy-p*0-10)))
     window.blit(fr,(CFG["x1"]+60,CFG["y2"]+15))
 
-    fr   = font15.render("dmx: 1."+str(dmx) ,1, (255,255,255))
+    fr   = font15.render("dmx: {}.{}".format(START_UNIV_A,dmx) ,1, (255,255,255))
     window.blit(fr,(CFG["x1"],CFG["y2"]+15))
 
 def GRID_DIM(dim,x,y):
@@ -2552,7 +2553,7 @@ def GRID_A2_DIM():
         a=options.grid_a2_idim
         draw_output_label(CFG,dim_raw,a,name="GRID_A2_DIM")
 
-def cvImageToSurface(cvImage):
+def cvImageToSurface(cvImage): 
     if cvImage.dtype.name == 'uint16':
         cvImage = (cvImage / 256).astype('uint8')
     size = cvImage.shape[1::-1]
@@ -2565,22 +2566,24 @@ def cvImageToSurface(cvImage):
     surface = pygame.image.frombuffer(cvImage.flatten(), size, format)
     return surface.convert_alpha() if format == 'RGBA' else surface.convert()
 
-def _img_meta():
+def create_img_meta():
     out = {}
-    out["pos"] = (70,430) # x,y
+    #40 235
+    out["pos"] = (0,0) # x,y
     out["ipos"] = (0,0) # x,y
     out["scale"] = 1
     out["dim"] = 100
     out["_fpath"] = '/opt/LibreLight/Xdesk/icon/'
     out["fname"] = "picker.png"
+    out["raw_img"] = ""
     out["img"] = ""
     out["err"] = []
     return out
 
-def _img_open(img_meta):
+def img_open(img_meta):
     fname = img_meta["_fpath"] +"/"+ img_meta["fname"] #'/opt/LibreLight/Xdesk/icon/picker.png'
-    image = cv2.imread(fname)
-    im2 = cvImageToSurface(image)
+    im2 = cv2.imread(fname)
+    img_meta["raw_img"] = im2
     img_meta["img"] = im2
     return im2
 
@@ -2589,17 +2592,40 @@ def img_jitter(img_meta):
     r2=random.randint(0,3)
     img_meta["ipos"] = [r1,r2]
 
+def img_rescale(img_meta, percent=75):
+    frame = img_meta["raw_img"]
+    width  = int(frame.shape[1] * percent/ 100)
+    height = int(frame.shape[0] * percent/ 100)
+    dim = (width, height)
+    return cv2.resize(frame, dim, interpolation =cv2.INTER_LINEAR)
+
+def __img_rescale(img_meta, percent=75):
+    img = img_meta["raw_img"]
+    print(img)
+    print(dir(img))
+    width  = int(img.get_width()  * percent/ 100)
+    height = int(img.get_height() * percent/ 100)
+    dim = (width, height)
+    print(dim)
+    return cv2.resize(img, dim) #, interpolation =cv2.INTER_LINEAR)
+
 def img_draw(img_meta):
 
-    img_jitter(img_meta)
+    #img_jitter(img_meta)
 
     pos  = img_meta["pos"]
     ipos = img_meta["ipos"]
     im2 = img_meta["img"]
-    window.blit(im2, (pos[0]+ipos[0], pos[1]+ipos[1])) 
+    im2 = img_rescale(img_meta, percent=175)
+
+
+    im2 = cvImageToSurface(im2)
+    w2 = int(im2.get_width()/2)
+    h2 = int(im2.get_height()/2)
+    window.blit(im2, (INPUT_START_POS_X-w2+pos[0]+ipos[0], INPUT_START_POS_Y-h2+pos[1]+ipos[1])) 
 
-img_meta_a = _img_meta()
-_img_open(img_meta_a)
+img_meta_a = create_img_meta()
+img_open(img_meta_a)
 
 t1 = Timer(143)
 time.sleep(0.33)
@@ -2615,8 +2641,8 @@ def main():
     global count_tilt
     global TEXT_BLOCK
     global TEXT_BLOCK_TIME
-    global PLAYLIST
-    global PLAYLIST_TIME
+    global MEDIALIST
+    global MEDIALIST_TIME
     global dataA
     global frame2
     global runnung
@@ -2631,9 +2657,9 @@ def main():
             TEXT_BLOCK = open_text_block()
             TEXT_BLOCK_TIME = time.time()
 
-        if  PLAYLIST_TIME+6 < time.time():
-            PLAYLIST = open_playlist()
-            PLAYLIST_TIME = time.time()
+        if  MEDIALIST_TIME+6 < time.time():
+            MEDIALIST = open_medialist()
+            MEDIALIST_TIME = time.time()
 
 
         pygame.display.flip()
@@ -2668,6 +2694,7 @@ def main():
 
         if VIDEO:
             draw_video(VIDEO)
+            img_draw(img_meta_a)
 
         if options.countdown:
             draw_counter(COUNTER)
@@ -2705,7 +2732,6 @@ def main():
         draw_overlay()
         pointer.draw(0,pm_wy) #wy
 
-        img_draw(img_meta_a)
 
 
         pygame.display.flip()