-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRCSystem.py
More file actions
executable file
·3175 lines (2610 loc) · 119 KB
/
Copy pathRCSystem.py
File metadata and controls
executable file
·3175 lines (2610 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Dongsheng Yang
# @Email: yang.dongsheng.46w@st.kyoto-u.ac.jp
# @Copyright = Copyright 2021, The Riken Robotics Project
# @Date: 2021-05-20 18:19:38
# @Last Modified by: dongshengyang
# @Last Modified time: 2024-03-8 09:21:38
'''
__author__ = "Dongsheng Yang"
__copyright__ = "Copyright 2021, The Riken Robotics Project"
__version__ = "1.0.0"
__maintainer__ = "Dongsheng Yang"
__email__ = "yang.dongsheng.46w@st.kyoto-u.ac.jp"
__status__ = "Developing"
'''
import random
from typing import Counter
from datetime import datetime
import defaultPose, mimicryExpParams
from collections import deque as deque
from deprecated import deprecated
# import socket
import threading
from threading import Thread
# import serial, itertools # used for Project 2, psychology experiment
import cv2, time, copy, sys, math, logging
import os, subprocess
import platform
import numpy as np
import pandas as pd
from bayes_opt import BayesianOptimization
from bayes_opt.logger import JSONLogger
from bayes_opt.event import Events
from bayes_opt import UtilityFunction
# from bayes_opt import acquisition
# ----- for ros------
import rospy, json, base64
from std_msgs.msg import String
import struct
# ----- for ros END------
# ----- for new model -----
# from SiameseRankNet import SiameseRankNet_analysis
from resmasknet import ResMaskNet
from intensityNet import *
# ----- for new model END -----
SPACE = ' '
LINUXVIDEOPATH = '/dev/video2' # ffplay # v4l2-ctl --list-devices
loopFlag = 0 # 0 - py-feat, 1 - human
FEAT_VERSION = 0 # 0 - py-feat 0.3.7 , 1 - py-feat 0.6.1
DEBUG = 0
# 0 - Run;
# 1 - Debuging with robot;
# 2 - Debug WITHOUT robot; for image debuging
# 3 - Debug without pic, with robot;
# 4 - Debug without pic, without robot;
# acq = acquisition.UpperConfidenceBound(kappa=2.5)
headYaw_fix_flag = False
headYaw_fix = 120
global smoothSleepTime
smoothSleepTime = 0.025
# pyfeat
from feat import Detector
detector = ''
# intensityModel
global intensityModel
intensityModel = ''
global rmn_model
rmn_model = ''
global facebox
facebox = ''
global feat_res
feat_res = []
global intensity_res
intensity_res = []
global mixed_res
mixed_res = []
class WebcamStreamWidget(object):
def __init__(self, stream_id=0, width=1280, height=720):
# initialize the video camera stream and read the first frame
print("[INFO]WebcamStreamWidget initializing...")
self.stream_id = stream_id # default is 0 for main camera
# opening video capture stream vcap
self.vcap = cv2.VideoCapture(stream_id)
# set resolution to 1920x1080
self.vcap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
self.vcap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
if not self.vcap.isOpened:
raise AttributeError("[ERROR]: Error accessing webcam stream.")
# reading a single frame from vcap stream for initializing
self.status , self.frame = self.vcap.read()
if not self.status:
print('[Exiting] No more frames to read')
raise Exception
# self.stopped is initialized to False
self.stopped = True
# thread instantiation
self.vthread = Thread(target=self.update, args=())
self.vthread.daemon = True # daemon threads run in background
print("[INFO]WebcamStreamWidget initialized.")
# start vthread
def start(self):
self.stopped = False
self.vthread.start()
# the target method passed to vthread for reading the next available frame
def update(self):
while True :
if self.stopped is True :
break
self.status, self.frame = self.vcap.read()
time.sleep(.01) # delay for simulating video processing
if self.status is False :
print('[Exiting] No more frames to read')
self.stopped = True
break
self.vcap.release()
def read(self):
return self.frame
# stop reading frames
def stop(self):
self.stopped = True
def save_frame(self, path):
if not self.stopped:
cv2.imwrite(path, self.read())
else:
raise AttributeError('frame not found')
# Video recording methods
def start_video_recording(self, path, codec='XVID', fps=60.0):
self.video_path = path
self.video_codec = codec
self.video_fps = fps
self.video_stopped = False
self.video_thread = Thread(target=self._record_video)
self.video_thread.daemon = True
self.video_thread.start()
def _record_video(self):
fourcc = cv2.VideoWriter_fourcc(*self.video_codec)
out = cv2.VideoWriter(self.video_path, fourcc, self.video_fps, (self.frame.shape[1], self.frame.shape[0]))
while not self.video_stopped:
if self.frame is not None:
out.write(self.frame)
time.sleep(1 / self.video_fps)
out.release()
print(f'Video saved to {self.video_path}')
def stop_video_recording(self):
self.video_stopped = True
if self.video_thread.is_alive():
self.video_thread.join()
class robot:
# initialization of robot
def __init__(self, duration=3, webcam=True, fps=60):
print("[INFO]robot initializing...")
# Return to normal state first
# Example: robotParams = {'1': 64, '2': 64, '3': 128, ...}
self.connection = True
self.robotParams = {}
self.executionCode = ''
self.stableState = [
64, 64, 128, 128, 128,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 32, 128, 128, headYaw_fix
]
# initialization of States, like [0, 0, 0, ... , 0]
self.lastState = self.stableState # initialization
self.nextState = self.stableState # initialization
# initialization of lastParams
self.lastParams = self.robotParams
self.defaultPose = defaultPose.defaultPose
self.AUPose = defaultPose.actionUnitParams
# Camera Parameters
if LINUXVIDEOPATH == '/dev/video2':
self.DEVICE_ID = 2
else:
self.DEVICE_ID = 0
self.WIDTH = 1280
self.HEIGHT = 720
self.FPS = fps
self.FRAMERATE = fps
self.counter = 0 # used in the fileName
self.fileName = ""
self.readablefileName = ''
self.VIDEOSIZE = "1280x720"
self.DURATION = duration
self.client = ""
self.photoform = '%01d.png'
# human experiment
self.bestImg = ""
# Final initialization
self.initialize_robotParams()
self.return_to_stable_state()
self.webcam = webcam
# webcam stream thread, initialize
if webcam:
self.webcam_stream_widget = WebcamStreamWidget(self.DEVICE_ID, self.WIDTH, self.HEIGHT)
self.webcam_stream_widget.start()
print("[INFO]robot and webcam initialized. Saving test img...")
self.webcam_stream_widget.save_frame('image_analysis/temp/test.png')
print("[INFO]test img saved.")
else:
print("[INFO]robot initialized.")
@deprecated(version='1.0', reason="FFmpeg will delay the program.")
def take_picture(self, isUsingCounter=True, appendix='', folder=''):
# we don't need this
# Allright, we need this
self.counter += 1
if isUsingCounter:
self.fileName = time.strftime("%Y_%m_%d_%H_%M_%S_No", time.localtime()) + str(self.counter)
if appendix:
self.fileName += "_" + appendix + self.photoform
else:
self.fileName += self.photoform
else:
self.fileName = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
if appendix:
self.fileName += "_" + appendix + self.photoform
else:
self.fileName += self.photoform
if DEBUG == 3 or DEBUG == 4:
print("Filename is {}".format(self.fileName))
return
if folder:
folderPath = "image_analysis/{}/".format(folder)
if not os.path.exists(folderPath):
try:
os.mkdir(folderPath)
except Exception as e:
print(e)
if not folder:
self.fileName = "image_analysis/temp/{}".format(self.fileName)
else:
self.fileName = folderPath + self.fileName
self.readablefileName = self.fileName[:-8] + '2.png'
if os.path.exists(self.fileName):
raise Exception("Same File!")
if "Linux" in platform.platform():
# Remember to check the path everytime.
videoPath = LINUXVIDEOPATH
fParam = "v4l2"
videoTypeParm = "-input_format"
elif "Windows" in platform.platform():
videoPath = "video='C922 Pro Stream Webcam'"
fParam = "dshow"
videoTypeParm = "-vcodec"
# only the command is different from take_video
command = "ffmpeg -f {} -i {} -vframes 2 {}".format(
fParam,
videoPath,
self.fileName)
# ffmpeg -f v4l2 -i /dev/video2 -vframes 1 /home/dongagent/github/CameraControl/algorithm/test.png
print(command)
if "Linux" in platform.platform():
# Linux
return subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
elif "Windows" in platform.platform():
# Windows
return subprocess.Popen(["pwsh", "-Command", command], stdout=subprocess.PIPE)
# Save pic from WebcamStreamWidget
def take_picture_cv(self, isUsingCounter=True, appendix='', folder=''):
self.counter += 1
if isUsingCounter:
self.fileName = time.strftime("%Y_%m_%d_%H_%M_%S_No", time.localtime()) + str(self.counter)
if appendix:
self.fileName += "_" + appendix + '.png'
else:
self.fileName += '.png'
else:
self.fileName = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
if appendix:
self.fileName += "_" + appendix + '.png'
else:
self.fileName += '.png'
if DEBUG == 3 or DEBUG == 4:
print("[take_picture_cv] Filename is {}".format(self.fileName))
return
if folder:
folderPath = "image_analysis/{}/".format(folder)
if not os.path.exists(folderPath):
try:
os.mkdir(folderPath)
except Exception as e:
print(e)
if not folder:
self.fileName = "image_analysis/temp/{}".format(self.fileName)
else:
self.fileName = folderPath + self.fileName
self.readablefileName = self.fileName
# save file in another thread
if self.readablefileName:
print('[INFO]Taking a photo...')
self.webcam_stream_widget.save_frame(self.readablefileName)
print('[INFO]frame captured.')
else:
raise ValueError('[ValueError] self.readablefileName is {}.'.format(self.readablefileName))
# use WebcamStreamWidget to take video
def start_taking_video(self, isUsingCounter=True, appendix='', folder=''):
self.counter += 1
if isUsingCounter:
self.fileName = str(self.counter) + '_' + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
if appendix:
self.fileName += "_" + appendix + ".mkv"
else:
self.fileName += ".mkv"
else:
self.fileName = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
if appendix:
self.fileName += "_" + appendix + ".mkv"
else:
self.fileName += ".mkv"
if DEBUG == 3 or DEBUG == 4:
print("Filename is {}".format(self.fileName))
return
if not os.path.exists('video_analysis/temp'):
os.makedirs('video_analysis/temp')
if folder:
folderPath = "video_analysis/{}/".format(folder)
if not os.path.exists(folderPath):
try:
os.makedirs(folderPath)
print('[INFO]make video folder')
except Exception as e:
print(e)
# setup filename
if not folder:
self.fileName = "video_analysis/temp/{}".format(self.fileName)
else:
self.fileName = folderPath + self.fileName
self.readablefileName = self.fileName
# save file in another thread
if self.readablefileName:
self.webcam_stream_widget.start_video_recording(self.readablefileName)
print('[INFO]video recording started.')
return 0
else:
raise ValueError('[ValueError] self.readablefileName is {}.'.format(self.readablefileName))
return 404
# stop video recording
def stop_taking_video(self):
self.webcam_stream_widget.stop_video_recording()
print('[INFO]video recording stopped.')
def initialize_robotParams(self):
# initialize robotParams like {"x1":0, "x2":0, ... , "x35": 0}
print("initialize_robotParams")
for i in range(1, 36):
codeNum = "x{}".format(i)
self.robotParams[codeNum] = 0
def return_to_stable_state(self):
# set all params in robotParams to 0
stableState = [
64, 64, 128, 128, 128,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 32, 128, 128, headYaw_fix
]
for i in range(1, 36):
self.robotParams["x{}".format(i)] = stableState[i - 1]
print("\n")
self.__check_robotParams()
# Drive the robot to the
self.connect_ros(True, False, steps=20)
time.sleep(0.5)
print("[INFO]return_to_stable_state")
def transfer_robotParams_to_states(self, params):
states = [0 for x in range(35)]
for i in range(1, 36):
states[i - 1] = params["x{}".format(i)]
return states
def switch_to_defaultPose(self, pose):
# pose number is [1,2,3,4,5,6, ,8,9,10, ,12,13,14,15,16]
# 1 標準 2 笑顔 3 怒り 4 悲しみ 5 驚き 6 微笑
# 7 None 8 くさい 9 ウィンク左 10 ウィンク右 11 None
# 12 「あ」 13「い」 14「う」 15「え」 16「お」
assert pose in [1,2,3,4,5,6,8,9,10,12,13,14,15,16], "ERROR! The selected pose is not existed."
poseNum = pose - 1
self.change_robotParams(self.defaultPose[poseNum])
def switch_to_customizedPose(self, customizedPose):
# Notice: customizedPose should clarify 35 axes
# E.g. [1, 2, 3, 0, ... , 255]
assert len(self.nextState) == 35, "ERROR! The customizedPose don't have 35 axes." + self.nextState
assert len(customizedPose) == 35, "ERROR! The customizedPose don't have 35 axes."
# States
self.lastState = self.nextState
self.nextState = customizedPose
if DEBUG >= 1:
print("[INFO]self.lastState", self.lastState)
print("[INFO]self.nextState", self.nextState)
# params
self.change_robotParams(customizedPose)
if DEBUG >= 1:
print(self.robotParams)
def change_robotParams(self, params):
# change robot params
assert isinstance(params, list), isinstance(params, list)
# Set the value of lastParams to be the current robotParams
self.lastParams = copy.deepcopy(self.robotParams)
# Construct current robotParams
for i in range(1, 36):
self.robotParams["x{}".format(i)] = params[i - 1]
self.__check_robotParams()
def sigmoid_smooth_execution_mode(self, steps = 20, total_time = 2, useScaledSigmoid=True, sigmoid_factor=10, debugmode=False):
if self.robotParams:
stepNum = steps
x_values_for_scaled_sigmoid = np.linspace(-3, 3, steps)
for i in range(0, stepNum):
# frab = (i + 1) / float(stepNum)
currentParams = {}
for k in self.lastParams.keys():
start = self.lastParams[k]
end = self.robotParams[k]
if useScaledSigmoid:
currentParams[k] = start + (end - start) * scaled_sigmoid(x_values_for_scaled_sigmoid[i])
else:
currentParams[k] = start + (end - start) * sigmoid(sigmoid_factor * (i / stepNum - 0.5))
if debugmode:
print('DEBUG:', currentParams)
self.nextState = self.transfer_robotParams_to_states(currentParams)
self.ros_talker()# Use ROS
# MODIFY HERE if you want to setup the duration of emotion
global smoothSleepTime
# if isSigmoidForTime:
# total_time = smoothSleepTime * steps
# time_interval = total_time * sigmoid(7 * (i / stepNum))
# # print(time_interval)
# time.sleep(time_interval)
# else:
time.sleep(smoothSleepTime)
def smooth_execution_mode(self, steps = 20, debugmode=False):
# steps: the middle steps between two robot expressions, default value is 5
if self.robotParams:
stepNum = steps
for i in range(0, stepNum):
frab = (i + 1) / float(stepNum)
currentParams = {}
for k in self.lastParams.keys():
interval = abs(self.lastParams[k] - self.robotParams[k]) * frab
currentParams[k] = int(self.lastParams[k] - interval) if self.lastParams[k] > self.robotParams[k] else int(self.lastParams[k] + interval)
# if k == "1":
# print(self.lastParams[k], self.robotParams[k], interval, currentParams[k])
if debugmode:
print('DEBUG:', currentParams)
self.nextState = self.transfer_robotParams_to_states(currentParams)
# self.__sendExecutionCode() # Use socket
self.ros_talker()# Use ROS
# MODIFY HERE if you want to setup the duration of emotion
global smoothSleepTime
time.sleep(smoothSleepTime)
# @deprecated
def normal_execution_mode(self):
# self.__sendExecutionCode() # Use socket
self.ros_talker()# Use ROS
def ros_talker(self):
rospy.init_node('rcpublisher', anonymous=True, disable_signals=True)
pub = rospy.Publisher('rc/command', String, queue_size=10)
sub = rospy.Subscriber('rc/return', String, self.sub_callback)
r = rospy.Rate(10) # speed
target = self.nextState
# if you wan to use MoveAllAxes
dictdata = {
"Command": "MoveAllAxes",
"Vals": list2string(target)
}
if not rospy.is_shutdown():
strdata = json.dumps(dictdata)
# print("strdata", strdata)
pub.publish(strdata)
# if rospy.Message:
# print(rospy.Message)
# r.sleep()
def sub_callback(self, data):
recv_dict = json.loads(data.data)
if recv_dict['Message'] == "PotentioValsBase64":
potval_bin = base64.b64decode(recv_dict['ValsBase64'])
potval = struct.unpack('%sB' % len(potval_bin), potval_bin)
potentio = list(potval)
print(potentio)
if recv_dict['Message'] == "PotentioVals":
potvalstr = recv_dict['Vals'].split(',')
potentio = map((lambda x: int(x)), potvalstr)
print(potentio)
if recv_dict['Message'] == "PotentioAxes":
potaxisstr = recv_dict['Axes'].split(',')
axiswithpotentio = map((lambda x: int(x)), potaxisstr)
print(axiswithpotentio)
# Send command to the robot
def connect_ros(self, isSmoothly=True, isRecording=False, appendix="", steps=20, timeIntervalBeforeExp=1, isUsingSigmoid=False,
sigmoid_factor=10, useScaledSigmoid=False, debugmode=False):
if DEBUG == 2 or DEBUG == 4:
print('you are DEBUGING')
return 0
try:
# self.ros_talker()
if self.connection:
# if we need to fix the headYaw, we need to change the value of x35 for every connect_ros
if headYaw_fix_flag:
self.robotParams["x35"] = headYaw_fix
# Start Record if isRecording
# if isRecording:
# # Please set which recording system you want to use. Video or image.
# process = self.start_taking_video(isUsingCounter=False, appendix=appendix)
# # time.sleep(1)
# Smoothly execute
if isSmoothly:
print("[INFO]Smoothly execution activated")
# if isRecording:
# time.sleep(timeIntervalBeforeExp) # Sleep 1 second by default to wait for the start of the video
if not isUsingSigmoid:
self.smooth_execution_mode(steps=steps, debugmode=debugmode)
else:
# using Sigmoid
self.sigmoid_smooth_execution_mode(steps=steps, useScaledSigmoid=useScaledSigmoid, sigmoid_factor=sigmoid_factor, debugmode=debugmode)
# Otherwise
else:
self.normal_execution_mode()
# self.client.close() # use ros now
# # Close Record
# if isRecording:
# process.wait()
# if process.returncode != 0:
# print(process.stdout.readlines())
# raise Exception("The subprocess does NOT end.")
else:
raise Exception("Connection Failed")
except rospy.ROSInterruptException:
print(rospy.ROSInterruptException)
return 0
# '''
def __check_robotParams(self):
# This function cannot be called outside
assert len(self.robotParams) == 35, "len(robotParams) != 35, {}".format(self.robotParams)
# give some restriction here
'''
### Axis (8, 9), (12, 13), (18, 19), (22, 23),
# we should use **a * b = 0 for each group. Which means,
# take (8, 9) for example. When axis 8 has value, we should make sure axis 9 is set to 0.**
**a * b = 0**
'''
assert self.robotParams["x8"] * self.robotParams["x9"] == 0 , print("x8:", self.robotParams["x8"], "\nx9:", self.robotParams["x9"])
assert self.robotParams["x12"] * self.robotParams["x13"] == 0, print("x12:", self.robotParams["x12"], "\nx13:", self.robotParams["x13"])
assert self.robotParams["x18"] * self.robotParams["x19"] == 0, print("x18:", self.robotParams["x18"], "\nx19:", self.robotParams["x19"])
assert self.robotParams["x22"] * self.robotParams["x23"] == 0, print("x22:", self.robotParams["x22"], "\nx23:", self.robotParams["x23"])
def robotChecker(self):
'''
check the robot with a neutral -> smile -> neutral procedure
'''
assert self.connection == True, "Connection is bad" # make sure the connection is good
self.return_to_stable_state() # Return to the stable state (標準Pose)
self.switch_to_defaultPose(2) # Switch to default pose 2 笑顔
self.connect_ros(isSmoothly=True, isRecording=False) # connect server and send the command to change facial expression smoothly
time.sleep(1)
self.return_to_stable_state() # Return to the stable state (標準Pose)
def perform_openface(self, figure):
# send figure to openface and get result
# TODO: Do something with openface
# Subprocess
openfacePath = ""
figurePath = ""
return openfacePath
def analysis(self, target_emotion_name):
assert target_emotion_name in ["Anger", "Disgust", "Fear", "Happiness", "Sadness", "Surprise"], "You are not using the predefine name"
py_feat_analysis(self.readablefileName, target_emotion_name)
def feedback(self):
pass
def list2string(data):
strtmp = ""
for val in data:
strtmp += str(val) + ","
retstr = strtmp.rstrip(',')
return retstr
def basicRunningCell(robotObject, commandSet, isRecordingFlag=False, steps=20):
rb = robotObject
for k,v in commandSet.items():
print("\n\n")
# Return to Standard Pose
rb.switch_to_customizedPose(rb.AUPose['StandardPose'])
rb.connect_ros(True, False)
# Go to the facial expressions
print("Switch to {}".format(k))
rb.switch_to_customizedPose(v)
rb.connect_ros(True, False, appendix="{}".format(k), steps=steps) # isSmoothly = True ,isRecording = True
# Return to Standard Pose
rb.switch_to_customizedPose(rb.AUPose['StandardPose'])
rb.connect_ros(True, False)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def scaled_sigmoid(x):
# x ~ [-3,3], y ~ [-1, 1]
return -0.052 + 1.105 * sigmoid(x)
def get_target(emotion_name):
# Anger, Disgust, Fear, Happiness, Sadness, Surprise, Neutral
# or lowercase
if emotion_name in ["Anger", "anger"]:
return 0
elif emotion_name in ["Disgust", "disgust"]:
return 1
elif emotion_name in ["Fear", "fear"]:
return 2
elif emotion_name in ["Happiness", "happiness"]:
return 3
elif emotion_name in ["Sadness", "sadness"]:
return 4
elif emotion_name in ["Surprise", "surprise"]:
return 5
elif emotion_name in ["Neutral", "neutral"]:
return 6
def py_feat_analysis(img, target_emotion, is_save_csv=True):
'''
# Use model directly
@img: file name
@target_emotion: Anger, Disgust, Fear, Happiness, Sadness, Surprise
'''
global rmn_model
global facebox
# method 1: use model directly
rmn_res = rmn_model.detect_emo(frame=cv2.imread(img), detected_face=[facebox])
output = rmn_res[0][get_target(target_emotion)]
new_df = pd.DataFrame(rmn_res, columns=["anger", "disgust", "fear", "happiness", "sadness", "surprise", "neutral"])
new_df['input'] = rb.readablefileName
for i, v in enumerate(['start_x', 'start_y', 'end_x', 'end_y']):
new_df[v] = facebox[i]
print('rmn_model: ', new_df)
if is_save_csv:
csv_emotion_name = img[:-4]+"_rmn_emotion.csv"
new_df.to_csv(csv_emotion_name)
if DEBUG > 0:
print("[INFO] new py_feat_analysis: {}".format(list(new_df[target_emotion])[0]))
# method 2: use old pyfeat to get output
# global detector
# image_prediction = detector.detect_image(img)
# df = image_prediction.head()
# if FEAT_VERSION == 0:
# emo_df = df.iloc[-1:,-8:] # feat 0.3.7
# elif FEAT_VERSION == 1:
# emo_df = df.iloc[-1:,-9:-1] # feat 0.5.0
# else:
# raise Exception("FEAT_VERSION is not correct")
# if is_save_csv:
# csv_name = img[:-4]+".csv"
# csv_emotion_name = img[:-4]+"_emotion.csv"
# df.to_csv(csv_name)
# emo_df.to_csv(csv_emotion_name)
# targetID = get_target(target_emotion)
# if DEBUG > 0:
# print("[INFO]py_feat_analysis: {}".format(list(df[target_emotion])[0]))
# # # return emo_df.iloc[0,targetID]
# output = list(df[target_emotion])[0]
return output
def setIntensityModel(target_emotion, facebox):
global intensityModel
# Load the model
# ['anger', 'disgust', 'fear', 'happiness', 'sadness', 'surprise']
print("target_emotion:", target_emotion)
if target_emotion.lower() in ["anger", 'angry']:
model_path = "new_models/angry_fold3_epoch7.pt"
elif target_emotion.lower() in ["disgust"]:
model_path = "new_models/disgust_fold3_epoch7.pt"
elif target_emotion.lower() in ["fear"]:
model_path = "new_models/fear_fold3_epoch6.pt"
elif target_emotion.lower() in ["happiness", "happy"]:
model_path = "new_models/happy_fold2_epoch7.pt"
elif target_emotion.lower() in ["sadness", "sad"]:
model_path = "new_models/sad_fold2_epoch6.pt"
elif target_emotion.lower() in ["surprise"]:
model_path = "new_models/surprise_fold3_epoch5.pt"
else:
model_path = ""
assert facebox, "facebox is empty"
intensityModel = IntensityNet_type1(model_path, facebox)
intensityModel.eval()
return 1
def intensityNet_analysis(img, target_emotion, is_save_csv=True):
# remember to set it before doing analysis
global intensityModel
# use intensityModel to detect emo
detection_res = intensityModel.detect_emo(Image.open(img))
detection_res = detection_res.tolist()
output = detection_res[get_target(target_emotion)]
# create a pd dataframe
detection_res = pd.DataFrame([detection_res], columns=["anger", "disgust", "fear", "happiness", "sadness", "surprise", "neutral"])
# add facebox info
detection_res['input'] = img
print('intensityModel: ', detection_res)
global facebox
for i, v in enumerate(['start_x', 'start_y', 'end_x', 'end_y']):
detection_res[v] = facebox[i]
if is_save_csv:
csv_emotion_name = img[:-4]+"_intensitynet.csv"
detection_res.to_csv(csv_emotion_name)
# result = tmp_res[target_emotion]
return output
# Function to calculate the mixed output with nonlinear transition using a sigmoid function
def calculate_output_nonlinear(A, B, threshold=0.75, alpha=0.8, B_min=0.39, B_max=0.64, output_min=0.75, output_max=1.2, k=10):
# If A is below or equal to the threshold, output A directly
if A <= threshold:
return A
# Scale B to fit within the desired range [output_min, output_max]
B_mapped = output_min + (B - B_min) * (output_max - output_min) / (B_max - B_min)
# Apply a sigmoid-based weight for smooth transition
weight = 1 / (1 + np.exp(-k * (A - threshold))) # Sigmoid function for smoother blending
# Calculate the smooth nonlinear mixed output
output = weight * (alpha * B_mapped + (1 - alpha) * A) + (1 - weight) * A
return output
def checkParameters(robotParams):
# Axis (8, 9), (12, 13), (18, 19), (22, 23),
# we should use a * b = 0 for each group.
# Which means, take (8, 9) for example.
# When axis 8 has value, we should make sure axis 9 is set to 0.
# DEPRECATED
# if robotParams[8-1] * robotParams[9-1] != 0:
# robotParams[np.random.choice([8-1, 9-1])] = 0
# new version, let's set one score p for [8, 12, 18, 22]. If p > 0, we do nothing. If p < 0, [8, 12, 18, 22] = 0, [9, 13, 19, 23] = p
if robotParams[8-1] < 0:
robotParams[9-1] = -robotParams[8-1]
robotParams[8-1] = 0
# x12 = x8, # x13 = x9, no need to be different
robotParams[12-1] = robotParams[8-1]
robotParams[13-1] = robotParams[9-1]
# DEPRECATED
# if robotParams[18-1] * robotParams[19-1] != 0:
# robotParams[np.random.choice([18-1, 19-1])] = 0
# new version
if robotParams[18-1] < 0:
robotParams[19-1] = -robotParams[18-1]
robotParams[18-1] = 0
# x22 = x18, x23 = x19
robotParams[22-1] = robotParams[18-1]
robotParams[23-1] = robotParams[19-1]
assert robotParams[8-1] * robotParams[9-1] == 0
assert robotParams[12-1] * robotParams[13-1] == 0
assert robotParams[18-1] * robotParams[19-1] == 0
assert robotParams[22-1] * robotParams[23-1] == 0
return robotParams
def fix_robot_param(fixedrobotcode):
# x2 = x1, use one axis for eyes upper lid
# fixedrobotcode[0] = 0
fixedrobotcode[1] = fixedrobotcode[0]
# x7 = x6, use one axis for eyes lower lid
fixedrobotcode[6] = fixedrobotcode[5]
# x12 = x8
fixedrobotcode[11] = fixedrobotcode[7]
# x13 = x9
fixedrobotcode[12] = fixedrobotcode[8]
# x14 = x10
fixedrobotcode[13] = fixedrobotcode[9]
# x17 = x16
fixedrobotcode[16] = fixedrobotcode[15]
# x22 = x18
fixedrobotcode[21] = fixedrobotcode[17]
# x23 = x19
fixedrobotcode[22] = fixedrobotcode[18]
# x24 = x20
fixedrobotcode[23] = fixedrobotcode[19]
# To open all axes
# x4 = x3
fixedrobotcode[3] = fixedrobotcode[2]
# x15 = x11
fixedrobotcode[14] = fixedrobotcode[10]
fixedrobotcode = checkParameters(fixedrobotcode)
return fixedrobotcode
# ------------
# **** BO ****
# ------------
def target_function(**kwargs):
"""Pyfeat evaluation object
Target
Maxmize the result of Pyfeat
"""
rb = kwargs['robot']
target_emotion = kwargs['target_emotion']
kwargs = kwargs["kwargs"]
print(kwargs)
# Get robot parameters
neutral = [86, 86, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 122]
if headYaw_fix_flag:
# modify the headYaw if we need to fix it
neutral[-1] = headYaw_fix
fixedrobotcode = copy.copy(neutral)
# dict = {}
for k,v in kwargs.items():
# print(k,v)
if "x" in k:
fixedrobotcode[int(k[1:])-1] = round(v)
fixedrobotcode = fix_robot_param(fixedrobotcode)
# control robot
if DEBUG > 0:
print("[INFO]fixedrobotcode is", fixedrobotcode)
rb.switch_to_customizedPose(fixedrobotcode)
global MYSTEPS
returncode = rb.connect_ros(isSmoothly=True, isRecording=False, steps=MYSTEPS) # isSmoothly = True ,isRecording = True
time.sleep(1)
# the sleep inside rb is not working for outside.
# -------------
# I need a feedback here!!
# -------------
# if returncode == 0:
# print('[INFO]successfully moved')
output = 0
global loopFlag
global COUNTER
# pyfeat_in_loop_output case
if loopFlag == 0:
# Take photo using cv2
COUNTER += 1
rb.take_picture_cv(isUsingCounter=False, appendix='{}_{}'.format(target_emotion, COUNTER), folder=target_emotion)
# Py-feat Analysis
print('[INFO]The {}th trial'.format(str(COUNTER)))
print('[INFO]target_emotion', target_emotion)
# check COUNTER is 1 or not
# assert COUNTER == 2 , "COUNTER is 2."
# Use Py-Feat 0.3.7
output_feat = py_feat_analysis(img=rb.readablefileName, target_emotion=target_emotion)
if target_emotion == 'anger':
threshold = 0.7106 * 0.8
B_max= 0.59
B_min= 0.36
elif target_emotion == 'disgust':
threshold = 0.9443 * 0.8
B_min = 0.37
B_max = 0.59
elif target_emotion == 'fear':
threshold = 0.3933 * 0.8
B_min = 0.19
B_max = 0.43
elif target_emotion == 'happiness':
threshold = 0.9832 * 0.8
B_min = 0.29
B_max = 0.55
elif target_emotion == 'sadness':
threshold = 0.6891 * 0.8
B_min = 0.36
B_max = 0.63
elif target_emotion == 'surprise':
threshold = 0.9842 * 0.8
B_min = 0.21
B_max = 0.43
output_inten = intensityNet_analysis(img=rb.readablefileName, target_emotion=target_emotion)
global feat_res
global intensity_res
global mixed_res
if COUNTER <= 30:
feat_res.append(round(output_feat, 6))
intensity_res.append(round(output_inten, 6))
else:
# Threshold=Min+α×(Max−Min)
alpha = 0.6
# if target_emotion == 'fear':
# alpha = 0.3
threshold1 = min(feat_res) + alpha * (max(feat_res) - min(feat_res))
my_list = sorted(feat_res)
# Calculate the index for the first 60% of the list
cutoff_index = int(len(my_list) * alpha)
threshold2 = my_list[cutoff_index]
threshold = min(threshold1, threshold2)
B_min = min(intensity_res)
B_max = max(intensity_res)
if COUNTER < 35:
print('threshold:', threshold)
print('intensity_res:', intensity_res)
print('B_min:', B_min, 'B_max:', B_max)
if COUNTER > 30 and output_feat > threshold:
# Use SiameseRankNet
# output_inten = intensityNet_analysis(img=rb.readablefileName, target_emotion=target_emotion)