diff --git a/.pylintrc b/.pylintrc index aa0e279a..0223b974 100644 --- a/.pylintrc +++ b/.pylintrc @@ -12,4 +12,4 @@ max-locals=16 max-returns=9 [FORMAT] -max-line-length=120 +max-line-length=119 diff --git a/continuous-integration/lint.sh b/continuous-integration/lint.sh index 4b3c1827..2c6d1f5d 100755 --- a/continuous-integration/lint.sh +++ b/continuous-integration/lint.sh @@ -8,7 +8,7 @@ pythonFiles=$(find "$SOURCE_DIR" -name '*.py' -not -path "*/ur_hand_eye_calibrat echo Running black on: echo "$pythonFiles" -black --check --diff $pythonFiles || exit $? +black --config="$ROOT_DIR/pyproject.toml" --check --diff $pythonFiles || exit $? echo Running flake8 on: echo "$pythonFiles" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..f5da6252 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,2 @@ +[tool.black] +line-length = 119 \ No newline at end of file diff --git a/source/applications/advanced/color_balance.py b/source/applications/advanced/color_balance.py index 504e324f..224946f8 100644 --- a/source/applications/advanced/color_balance.py +++ b/source/applications/advanced/color_balance.py @@ -72,9 +72,7 @@ def _set_settings(dimension, iris, exposure_time, brightness, gain): settings.brightness = brightness settings.gain = gain else: - raise ValueError( - f"The dimension value should be '3d' or '2d', got: '{dimension}'" - ) + raise ValueError(f"The dimension value should be '3d' or '2d', got: '{dimension}'") return settings @@ -195,16 +193,10 @@ def _color_balance_calibration(camera, settings_3d): f"{int(mean_color.blue)} " ) ) - if int(mean_color.green) == int(mean_color.red) and int( - mean_color.green - ) == int(mean_color.blue): + if int(mean_color.green) == int(mean_color.red) and int(mean_color.green) == int(mean_color.blue): break - corrected_red_balance = ( - camera.settings.red_balance * mean_color.green / mean_color.red - ) - corrected_blue_balance = ( - camera.settings.blue_balance * mean_color.green / mean_color.blue - ) + corrected_red_balance = camera.settings.red_balance * mean_color.green / mean_color.red + corrected_blue_balance = camera.settings.blue_balance * mean_color.green / mean_color.blue _display_rgb(rgb, "RGB image after color balance (3D capture)") return (corrected_red_balance, corrected_blue_balance) diff --git a/source/applications/advanced/create_depth_map.py b/source/applications/advanced/create_depth_map.py index bf22764f..8d1598c5 100644 --- a/source/applications/advanced/create_depth_map.py +++ b/source/applications/advanced/create_depth_map.py @@ -23,9 +23,7 @@ def _main(): depth_map = np.dstack([point_cloud["z"]]) depth_map_uint8 = ( - (depth_map - np.nanmin(depth_map)) - / (np.nanmax(depth_map) - np.nanmin(depth_map)) - * 255 + (depth_map - np.nanmin(depth_map)) / (np.nanmax(depth_map) - np.nanmin(depth_map)) * 255 ).astype(np.uint8) # Applying color map diff --git a/source/applications/advanced/downsample.py b/source/applications/advanced/downsample.py index 48b3f082..a9fbcf54 100644 --- a/source/applications/advanced/downsample.py +++ b/source/applications/advanced/downsample.py @@ -23,9 +23,7 @@ def _gridsum(matrix, downsampling_factor): Returns: Matrix reshaped and summed in second direction. """ - return _sumline( - np.transpose(_sumline(matrix, downsampling_factor)), downsampling_factor - ) + return _sumline(np.transpose(_sumline(matrix, downsampling_factor)), downsampling_factor) def _sumline(matrix, downsampling_factor): @@ -41,9 +39,7 @@ def _sumline(matrix, downsampling_factor): Matrix reshaped and summed in first direction. """ return np.transpose( - np.nansum( - np.transpose(np.transpose(matrix).reshape(-1, downsampling_factor)), 0 - ).reshape( + np.nansum(np.transpose(np.transpose(matrix).reshape(-1, downsampling_factor)), 0).reshape( int(np.shape(np.transpose(matrix))[0]), int(np.shape(np.transpose(matrix))[1] / downsampling_factor), ) @@ -69,12 +65,8 @@ def _downsample(xyz, rgb, contrast, downsampling_factor): """ # Checking if downsampling_factor is ok - if fmod(rgb.shape[0], downsampling_factor) or fmod( - rgb.shape[1], downsampling_factor - ): - raise ValueError( - "Downsampling factor has to be a factor of point cloud width (1920) and height (1200)." - ) + if fmod(rgb.shape[0], downsampling_factor) or fmod(rgb.shape[1], downsampling_factor): + raise ValueError("Downsampling factor has to be a factor of point cloud width (1920) and height (1200).") rgb_new = np.zeros( ( @@ -86,8 +78,7 @@ def _downsample(xyz, rgb, contrast, downsampling_factor): ) for i in range(3): rgb_new[:, :, i] = ( - (np.transpose(_gridsum(rgb[:, :, i], downsampling_factor))) - / (downsampling_factor * downsampling_factor) + (np.transpose(_gridsum(rgb[:, :, i], downsampling_factor))) / (downsampling_factor * downsampling_factor) ).astype(np.uint8) contrast[np.isnan(xyz[:, :, 2])] = 0 diff --git a/source/applications/advanced/gamma_correction.py b/source/applications/advanced/gamma_correction.py index 5102a196..2fa3a7fc 100644 --- a/source/applications/advanced/gamma_correction.py +++ b/source/applications/advanced/gamma_correction.py @@ -16,10 +16,7 @@ def _options(): """ parser = argparse.ArgumentParser( - description=( - "Capture 2D image and apply gamma correction\n" - "Example:\n\t $ python gamma_correction.py 2" - ), + description=("Capture 2D image and apply gamma correction\n" "Example:\n\t $ python gamma_correction.py 2"), formatter_class=argparse.RawTextHelpFormatter, ) @@ -44,9 +41,7 @@ def adjust_gamma(image, gamma: float): # build a lookup table mapping the pixel values [0, 255] to # their adjusted gamma values inv_gamma = 1.0 / gamma - table = np.array( - [((i / 255.0) ** inv_gamma) * 255 for i in np.arange(0, 256)] - ).astype("uint8") + table = np.array([((i / 255.0) ** inv_gamma) * 255 for i in np.arange(0, 256)]).astype("uint8") # apply gamma correction using the lookup table return cv2.LUT(image, table) diff --git a/source/applications/advanced/hand_eye_calibration/calibrate_eye_to_hand.py b/source/applications/advanced/hand_eye_calibration/calibrate_eye_to_hand.py index 6d4e59f1..aa1e90da 100644 --- a/source/applications/advanced/hand_eye_calibration/calibrate_eye_to_hand.py +++ b/source/applications/advanced/hand_eye_calibration/calibrate_eye_to_hand.py @@ -19,8 +19,7 @@ def _acquire_checkerboard_frame(camera): def _enter_robot_pose(index): inputted = input( - f"Enter pose with id={index} (a line with 16 space separated values" - " describing 4x4 row-major matrix):" + f"Enter pose with id={index} (a line with 16 space separated values" " describing 4x4 row-major matrix):" ) elements = inputted.split(maxsplit=15) data = np.array(elements, dtype=np.float64).reshape((4, 4)) @@ -38,9 +37,7 @@ def _main(): calibrate = False while not calibrate: - command = input( - "Enter command, p (to add robot pose) or c (to perform calibration):" - ).strip() + command = input("Enter command, p (to add robot pose) or c (to perform calibration):").strip() if command == "p": try: robot_pose = _enter_robot_pose(current_pose_id) diff --git a/source/applications/advanced/hand_eye_calibration/pose_conversions.py b/source/applications/advanced/hand_eye_calibration/pose_conversions.py index e9a92cd3..4bcfe620 100644 --- a/source/applications/advanced/hand_eye_calibration/pose_conversions.py +++ b/source/applications/advanced/hand_eye_calibration/pose_conversions.py @@ -232,12 +232,8 @@ def roll_pitch_yaw_to_rotation_matrix(rpy_list): """ for rotation in rpy_list: - rotation_matrix = R.from_euler( - rotation["convention"].value, rotation["roll_pitch_yaw"] - ).as_matrix() - print( - f"Rotation Matrix from Roll-Pitch-Yaw angles ({rotation['convention'].name}):" - ) + rotation_matrix = R.from_euler(rotation["convention"].value, rotation["roll_pitch_yaw"]).as_matrix() + print(f"Rotation Matrix from Roll-Pitch-Yaw angles ({rotation['convention'].name}):") print(f"{rotation_matrix}") diff --git a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_binary_writer.py b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_binary_writer.py index 5f1e3a67..4db4645c 100644 --- a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_binary_writer.py +++ b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_binary_writer.py @@ -22,16 +22,17 @@ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys -sys.path.append('..') + +sys.path.append("..") import struct from rtde import serialize + class CSVBinaryWriter(object): - - def __init__(self, file, names, types, delimiter=' '): + def __init__(self, file, names, types, delimiter=" "): if len(names) != len(types): - raise ValueError('List sizes are not identical.') + raise ValueError("List sizes are not identical.") self.__file = file self.__names = names self.__types = types @@ -43,75 +44,146 @@ def __init__(self, file, names, types, delimiter=' '): self.__columns += size if size > 1: for j in range(size): - name = self.__names[i]+'_'+str(j) + name = self.__names[i] + "_" + str(j) self.__header_names.append(name) else: name = self.__names[i] self.__header_names.append(name) - + def getType(self, vtype): - if(vtype == 'VECTOR3D'): + if vtype == "VECTOR3D": return "DOUBLE" + self.__delimiter + "DOUBLE" + self.__delimiter + "DOUBLE" - elif(vtype == 'VECTOR6D'): - return "DOUBLE" + self.__delimiter + "DOUBLE" + self.__delimiter + "DOUBLE" + self.__delimiter + "DOUBLE" + self.__delimiter + "DOUBLE" + self.__delimiter + "DOUBLE" - elif(vtype == 'VECTOR6INT32'): - return "INT32" + self.__delimiter + "INT32" + self.__delimiter + "INT32" + self.__delimiter + "INT32" + self.__delimiter + "INT32" + self.__delimiter + "INT32" - elif(vtype == 'VECTOR6UINT32'): - return "UINT32" + self.__delimiter + "UINT32" + self.__delimiter + "UINT32" + self.__delimiter + "UINT32" + self.__delimiter + "UINT32" + self.__delimiter + "UINT32" + elif vtype == "VECTOR6D": + return ( + "DOUBLE" + + self.__delimiter + + "DOUBLE" + + self.__delimiter + + "DOUBLE" + + self.__delimiter + + "DOUBLE" + + self.__delimiter + + "DOUBLE" + + self.__delimiter + + "DOUBLE" + ) + elif vtype == "VECTOR6INT32": + return ( + "INT32" + + self.__delimiter + + "INT32" + + self.__delimiter + + "INT32" + + self.__delimiter + + "INT32" + + self.__delimiter + + "INT32" + + self.__delimiter + + "INT32" + ) + elif vtype == "VECTOR6UINT32": + return ( + "UINT32" + + self.__delimiter + + "UINT32" + + self.__delimiter + + "UINT32" + + self.__delimiter + + "UINT32" + + self.__delimiter + + "UINT32" + + self.__delimiter + + "UINT32" + ) else: return str(vtype) - def writeheader(self): - #Header names - headerStr=str("") + # Header names + headerStr = str("") for i in range(len(self.__header_names)): - if(i != 0): + if i != 0: headerStr += self.__delimiter headerStr += self.__header_names[i] headerStr += "\n" - self.__file.write(struct.pack(str(len(headerStr)) + 's', headerStr)) + self.__file.write(struct.pack(str(len(headerStr)) + "s", headerStr)) - #Header types - typeStr=str("") + # Header types + typeStr = str("") for i in range(len(self.__names)): - if(i != 0): + if i != 0: typeStr += self.__delimiter typeStr += self.getType(self.__types[i]) typeStr += "\n" - self.__file.write(struct.pack(str(len(typeStr)) + 's', typeStr)) + self.__file.write(struct.pack(str(len(typeStr)) + "s", typeStr)) - def packToBinary(self, vtype, value): print(vtype) - if(vtype == 'BOOL'): + if vtype == "BOOL": print("isBOOL" + str(value)) - if(vtype == 'UINT8'): + if vtype == "UINT8": print("isUINT8" + str(value)) - elif(vtype == 'INT32'): + elif vtype == "INT32": print("isINT32" + str(value)) - elif(vtype == 'INT64'): + elif vtype == "INT64": print("isINT64" + str(value)) - elif(vtype == 'UINT32'): + elif vtype == "UINT32": print("isUINT32" + str(value)) - elif(vtype == 'UINT64'): + elif vtype == "UINT64": print("isUINT64" + str(value)) - elif(vtype == 'DOUBLE'): + elif vtype == "DOUBLE": print("isDOUBLE" + str(value) + str(type(value)) + str(sys.getsizeof(value))) - elif(vtype == 'VECTOR3D'): - print("isVECTOR3D" + str(value[0]) + ","+ str(value[1]) + ","+ str(value[2])) - elif(vtype == 'VECTOR6D'): - print("isVECTOR6D" + str(value[0]) + ","+ str(value[1]) + ","+ str(value[2]) + ","+ str(value[3]) + ","+ str(value[4]) + ","+ str(value[5])) - elif(vtype == 'VECTOR6INT32'): - print("isVECTOR6INT32" + str(value[0]) + ","+ str(value[1]) + ","+ str(value[2]) + ","+ str(value[3]) + ","+ str(value[4]) + ","+ str(value[5])) - elif(vtype == 'VECTOR6UINT32'): - print("isVECTOR6UINT32" + str(value[0]) + ","+ str(value[1]) + ","+ str(value[2]) + ","+ str(value[3]) + ","+ str(value[4]) + ","+ str(value[5])) + elif vtype == "VECTOR3D": + print("isVECTOR3D" + str(value[0]) + "," + str(value[1]) + "," + str(value[2])) + elif vtype == "VECTOR6D": + print( + "isVECTOR6D" + + str(value[0]) + + "," + + str(value[1]) + + "," + + str(value[2]) + + "," + + str(value[3]) + + "," + + str(value[4]) + + "," + + str(value[5]) + ) + elif vtype == "VECTOR6INT32": + print( + "isVECTOR6INT32" + + str(value[0]) + + "," + + str(value[1]) + + "," + + str(value[2]) + + "," + + str(value[3]) + + "," + + str(value[4]) + + "," + + str(value[5]) + ) + elif vtype == "VECTOR6UINT32": + print( + "isVECTOR6UINT32" + + str(value[0]) + + "," + + str(value[1]) + + "," + + str(value[2]) + + "," + + str(value[3]) + + "," + + str(value[4]) + + "," + + str(value[5]) + ) def writerow(self, data_object): self.__file.write(data_object) - - \ No newline at end of file diff --git a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_reader.py b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_reader.py index 0401001b..2e6cc27e 100644 --- a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_reader.py +++ b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_reader.py @@ -30,20 +30,22 @@ _log = logging.getLogger(LOGNAME) -runtime_state = 'runtime_state' -runtime_state_running = '2' +runtime_state = "runtime_state" +runtime_state_running = "2" + class CSVReader(object): __samples = None __filename = None - def get_header_data(self,__reader): + + def get_header_data(self, __reader): header = next(__reader) return header - def __init__(self, csvfile, delimiter = ' ', filter_running_program=False): + def __init__(self, csvfile, delimiter=" ", filter_running_program=False): self.__filename = csvfile.name - csvfile = [csvfile for csvfile in csvfile.readlines() if csvfile.strip()] # remove any empty lines + csvfile = [csvfile for csvfile in csvfile.readlines() if csvfile.strip()] # remove any empty lines reader = csv.reader(csvfile, delimiter=delimiter) header = self.get_header_data(reader) @@ -51,13 +53,13 @@ def __init__(self, csvfile, delimiter = ' ', filter_running_program=False): # read csv file data = [row for row in reader] - if len(data)==0: - _log.warn('No data read from file: ' + self.__filename) + if len(data) == 0: + _log.warn("No data read from file: " + self.__filename) # filter data if filter_running_program: if runtime_state not in header: - _log.warn('Unable to filter data since runtime_state field is missing in data set') + _log.warn("Unable to filter data since runtime_state field is missing in data set") else: idx = header.index(runtime_state) data = [row for row in data if row[idx] == runtime_state_running] @@ -65,7 +67,7 @@ def __init__(self, csvfile, delimiter = ' ', filter_running_program=False): self.__samples = len(data) if self.__samples == 0: - _log.warn('No data left from file: ' + self.__filename + ' after filtering') + _log.warn("No data left from file: " + self.__filename + " after filtering") # transpose data data = list(zip(*data)) diff --git a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_writer.py b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_writer.py index 1011b2a2..4717dc72 100644 --- a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_writer.py +++ b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/csv_writer.py @@ -24,15 +24,16 @@ import csv import sys -sys.path.append('..') + +sys.path.append("..") from rtde import serialize + class CSVWriter(object): - - def __init__(self, csvfile, names, types, delimiter=' '): + def __init__(self, csvfile, names, types, delimiter=" "): if len(names) != len(types): - raise ValueError('List sizes are not identical.') + raise ValueError("List sizes are not identical.") self.__names = names self.__types = types self.__header_names = [] @@ -42,16 +43,16 @@ def __init__(self, csvfile, names, types, delimiter=' '): self.__columns += size if size > 1: for j in range(size): - name = self.__names[i]+'_'+str(j) + name = self.__names[i] + "_" + str(j) self.__header_names.append(name) else: name = self.__names[i] self.__header_names.append(name) self.__writer = csv.writer(csvfile, delimiter=delimiter) - + def writeheader(self): self.__writer.writerow(self.__header_names) - + def writerow(self, data_object): data = [] for i in range(len(self.__names)): @@ -62,4 +63,3 @@ def writerow(self, data_object): else: data.append(value) self.__writer.writerow(data) - \ No newline at end of file diff --git a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/rtde.py b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/rtde.py index 977e8897..8bfb35eb 100644 --- a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/rtde.py +++ b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/rtde.py @@ -28,41 +28,45 @@ import logging if sys.version_info[0] < 3: - import serialize + import serialize else: - from rtde import serialize + from rtde import serialize DEFAULT_TIMEOUT = 1.0 -LOGNAME = 'rtde' +LOGNAME = "rtde" _log = logging.getLogger(LOGNAME) class Command: - RTDE_REQUEST_PROTOCOL_VERSION = 86 # ascii V - RTDE_GET_URCONTROL_VERSION = 118 # ascii v - RTDE_TEXT_MESSAGE = 77 # ascii M - RTDE_DATA_PACKAGE = 85 # ascii U - RTDE_CONTROL_PACKAGE_SETUP_OUTPUTS = 79 # ascii O - RTDE_CONTROL_PACKAGE_SETUP_INPUTS = 73 # ascii I - RTDE_CONTROL_PACKAGE_START = 83 # ascii S - RTDE_CONTROL_PACKAGE_PAUSE = 80 # ascii P + RTDE_REQUEST_PROTOCOL_VERSION = 86 # ascii V + RTDE_GET_URCONTROL_VERSION = 118 # ascii v + RTDE_TEXT_MESSAGE = 77 # ascii M + RTDE_DATA_PACKAGE = 85 # ascii U + RTDE_CONTROL_PACKAGE_SETUP_OUTPUTS = 79 # ascii O + RTDE_CONTROL_PACKAGE_SETUP_INPUTS = 73 # ascii I + RTDE_CONTROL_PACKAGE_START = 83 # ascii S + RTDE_CONTROL_PACKAGE_PAUSE = 80 # ascii P RTDE_PROTOCOL_VERSION = 2 + class ConnectionState: DISCONNECTED = 0 CONNECTED = 1 STARTED = 2 PAUSED = 3 + class RTDEException(Exception): def __init__(self, msg): self.msg = msg + def __str__(self): return repr(self.msg) + class RTDE(object): def __init__(self, hostname, port=30004): self.hostname = hostname @@ -76,7 +80,7 @@ def connect(self): if self.__sock: return - self.__buf = b'' # buffer data in binary format + self.__buf = b"" # buffer data in binary format try: self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) @@ -88,7 +92,7 @@ def connect(self): self.__sock = None raise if not self.negotiate_protocol_version(): - raise RTDEException('Unable to negotiate protocol version') + raise RTDEException("Unable to negotiate protocol version") def disconnect(self): if self.__sock: @@ -103,7 +107,16 @@ def get_controller_version(self): cmd = Command.RTDE_GET_URCONTROL_VERSION version = self.__sendAndReceive(cmd) if version: - _log.info('Controller version: ' + str(version.major) + '.' + str(version.minor) + '.' + str(version.bugfix)+ '.' + str(version.build)) + _log.info( + "Controller version: " + + str(version.major) + + "." + + str(version.minor) + + "." + + str(version.bugfix) + + "." + + str(version.build) + ) if version.major == 3 and version.minor <= 2 and version.bugfix < 19171: _log.error("Please upgrade your controller to minimally version 3.2.19171") sys.exit() @@ -112,18 +125,16 @@ def get_controller_version(self): def negotiate_protocol_version(self): cmd = Command.RTDE_REQUEST_PROTOCOL_VERSION - payload = struct.pack('>H', RTDE_PROTOCOL_VERSION) + payload = struct.pack(">H", RTDE_PROTOCOL_VERSION) success = self.__sendAndReceive(cmd, payload) return success def send_input_setup(self, variables, types=[]): cmd = Command.RTDE_CONTROL_PACKAGE_SETUP_INPUTS - payload = bytearray(','.join(variables), 'utf-8') + payload = bytearray(",".join(variables), "utf-8") result = self.__sendAndReceive(cmd, payload) - if len(types)!=0 and not self.__list_equals(result.types, types): - _log.error('Data type inconsistency for input setup: ' + - str(types) + ' - ' + - str(result.types)) + if len(types) != 0 and not self.__list_equals(result.types, types): + _log.error("Data type inconsistency for input setup: " + str(types) + " - " + str(result.types)) return None result.names = variables self.__input_config[result.id] = result @@ -131,13 +142,11 @@ def send_input_setup(self, variables, types=[]): def send_output_setup(self, variables, types=[], frequency=125): cmd = Command.RTDE_CONTROL_PACKAGE_SETUP_OUTPUTS - payload = struct.pack('>d', frequency) - payload = payload + (','.join(variables).encode('utf-8')) + payload = struct.pack(">d", frequency) + payload = payload + (",".join(variables).encode("utf-8")) result = self.__sendAndReceive(cmd, payload) - if len(types)!=0 and not self.__list_equals(result.types, types): - _log.error('Data type inconsistency for output setup: ' + - str(types) + ' - ' + - str(result.types)) + if len(types) != 0 and not self.__list_equals(result.types, types): + _log.error("Data type inconsistency for output setup: " + str(types) + " - " + str(result.types)) return False result.names = variables self.__output_config = result @@ -147,44 +156,44 @@ def send_start(self): cmd = Command.RTDE_CONTROL_PACKAGE_START success = self.__sendAndReceive(cmd) if success: - _log.info('RTDE synchronization started') + _log.info("RTDE synchronization started") self.__conn_state = ConnectionState.STARTED else: - _log.error('RTDE synchronization failed to start') + _log.error("RTDE synchronization failed to start") return success def send_pause(self): cmd = Command.RTDE_CONTROL_PACKAGE_PAUSE success = self.__sendAndReceive(cmd) if success: - _log.info('RTDE synchronization paused') + _log.info("RTDE synchronization paused") self.__conn_state = ConnectionState.PAUSED else: - _log.error('RTDE synchronization failed to pause') + _log.error("RTDE synchronization failed to pause") return success def send(self, input_data): if self.__conn_state != ConnectionState.STARTED: - _log.error('Cannot send when RTDE synchronization is inactive') + _log.error("Cannot send when RTDE synchronization is inactive") return if not input_data.recipe_id in self.__input_config: - _log.error('Input configuration id not found: ' + str(input_data.recipe_id)) + _log.error("Input configuration id not found: " + str(input_data.recipe_id)) return config = self.__input_config[input_data.recipe_id] return self.__sendall(Command.RTDE_DATA_PACKAGE, config.pack(input_data)) def receive(self, binary=False): if self.__output_config is None: - _log.error('Output configuration not initialized') + _log.error("Output configuration not initialized") return None if self.__conn_state != ConnectionState.STARTED: - _log.error('Cannot receive when RTDE synchronization is inactive') + _log.error("Cannot receive when RTDE synchronization is inactive") return None return self.__recv(Command.RTDE_DATA_PACKAGE, binary) - def send_message(self, message, source = "Python Client", type = serialize.Message.INFO_MESSAGE): + def send_message(self, message, source="Python Client", type=serialize.Message.INFO_MESSAGE): cmd = Command.RTDE_TEXT_MESSAGE - fmt = '>B%dsB%dsB' % (len(message), len(source)) + fmt = ">B%dsB%dsB" % (len(message), len(source)) payload = struct.pack(fmt, len(message), message, len(source), source, type) return self.__sendall(cmd, payload) @@ -206,21 +215,21 @@ def __on_packet(self, cmd, payload): elif cmd == Command.RTDE_DATA_PACKAGE: return self.__unpack_data_package(payload, self.__output_config) else: - _log.error('Unknown package command: ' + str(cmd)) + _log.error("Unknown package command: " + str(cmd)) - def __sendAndReceive(self, cmd, payload=b''): + def __sendAndReceive(self, cmd, payload=b""): if self.__sendall(cmd, payload): return self.__recv(cmd) else: return None - def __sendall(self, command, payload=b''): - fmt = '>HB' + def __sendall(self, command, payload=b""): + fmt = ">HB" size = struct.calcsize(fmt) + len(payload) buf = struct.pack(fmt, size, command) + payload if self.__sock is None: - _log.error('Unable to send: not connected to Robot') + _log.error("Unable to send: not connected to Robot") return False _, writable, _ = select.select([], [self.__sock], [], DEFAULT_TIMEOUT) @@ -234,7 +243,7 @@ def __sendall(self, command, payload=b''): def has_data(self): timeout = 0 readable, _, _ = select.select([self.__sock], [], [], timeout) - return len(readable)!=0 + return len(readable) != 0 def __recv(self, command, binary=False): while self.is_connected(): @@ -246,8 +255,8 @@ def __recv(self, command, binary=False): return None self.__buf = self.__buf + more - if len(xlist) or len(readable) == 0: # Effectively a timeout of DEFAULT_TIMEOUT seconds - _log.info('lost connection with controller') + if len(xlist) or len(readable) == 0: # Effectively a timeout of DEFAULT_TIMEOUT seconds + _log.info("lost connection with controller") self.__trigger_disconnected() return None @@ -257,86 +266,85 @@ def __recv(self, command, binary=False): packet_header = serialize.ControlHeader.unpack(self.__buf) if len(self.__buf) >= packet_header.size: - packet, self.__buf = self.__buf[3:packet_header.size], self.__buf[packet_header.size:] + packet, self.__buf = self.__buf[3 : packet_header.size], self.__buf[packet_header.size :] data = self.__on_packet(packet_header.command, packet) if len(self.__buf) >= 3 and command == Command.RTDE_DATA_PACKAGE: next_packet_header = serialize.ControlHeader.unpack(self.__buf) if next_packet_header.command == command: - _log.info('skipping package(1)') + _log.info("skipping package(1)") continue if packet_header.command == command: - if(binary): + if binary: return packet[1:] return data else: - _log.info('skipping package(2)') + _log.info("skipping package(2)") else: break return None def __trigger_disconnected(self): _log.info("RTDE disconnected") - self.disconnect() #clean-up + self.disconnect() # clean-up def __unpack_protocol_version_package(self, payload): if len(payload) != 1: - _log.error('RTDE_REQUEST_PROTOCOL_VERSION: Wrong payload size') + _log.error("RTDE_REQUEST_PROTOCOL_VERSION: Wrong payload size") return None result = serialize.ReturnValue.unpack(payload) return result.success def __unpack_urcontrol_version_package(self, payload): if len(payload) != 16: - _log.error('RTDE_GET_URCONTROL_VERSION: Wrong payload size') + _log.error("RTDE_GET_URCONTROL_VERSION: Wrong payload size") return None version = serialize.ControlVersion.unpack(payload) return version def __unpack_text_message(self, payload): if len(payload) < 1: - _log.error('RTDE_TEXT_MESSAGE: No payload') + _log.error("RTDE_TEXT_MESSAGE: No payload") return None msg = serialize.Message.unpack(payload) - if(msg.level == serialize.Message.EXCEPTION_MESSAGE or - msg.level == serialize.Message.ERROR_MESSAGE): - _log.error(msg.source + ': ' + msg.message) + if msg.level == serialize.Message.EXCEPTION_MESSAGE or msg.level == serialize.Message.ERROR_MESSAGE: + _log.error(msg.source + ": " + msg.message) elif msg.level == serialize.Message.WARNING_MESSAGE: - _log.warning(msg.source + ': ' + msg.message) + _log.warning(msg.source + ": " + msg.message) elif msg.level == serialize.Message.INFO_MESSAGE: - _log.info(msg.source + ': ' + msg.message) + _log.info(msg.source + ": " + msg.message) def __unpack_setup_outputs_package(self, payload): if len(payload) < 1: - _log.error('RTDE_CONTROL_PACKAGE_SETUP_OUTPUTS: No payload') + _log.error("RTDE_CONTROL_PACKAGE_SETUP_OUTPUTS: No payload") return None output_config = serialize.DataConfig.unpack_recipe(payload) return output_config def __unpack_setup_inputs_package(self, payload): if len(payload) < 1: - _log.error('RTDE_CONTROL_PACKAGE_SETUP_INPUTS: No payload') + _log.error("RTDE_CONTROL_PACKAGE_SETUP_INPUTS: No payload") return None input_config = serialize.DataConfig.unpack_recipe(payload) return input_config def __unpack_start_package(self, payload): if len(payload) != 1: - _log.error('RTDE_CONTROL_PACKAGE_START: Wrong payload size') + _log.error("RTDE_CONTROL_PACKAGE_START: Wrong payload size") return None result = serialize.ReturnValue.unpack(payload) return result.success def __unpack_pause_package(self, payload): if len(payload) != 1: - _log.error('RTDE_CONTROL_PACKAGE_PAUSE: Wrong payload size') + _log.error("RTDE_CONTROL_PACKAGE_PAUSE: Wrong payload size") return None result = serialize.ReturnValue.unpack(payload) return result.success def __unpack_data_package(self, payload, output_config): if output_config is None: - _log.error('RTDE_DATA_PACKAGE: Missing output configuration') + _log.error("RTDE_DATA_PACKAGE: Missing output configuration") return None output = output_config.unpack(payload) return output diff --git a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/rtde_config.py b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/rtde_config.py index 066f0856..7e7d9b0e 100644 --- a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/rtde_config.py +++ b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/rtde_config.py @@ -25,13 +25,14 @@ class Recipe(object): - __slots__=['key', 'names', 'types'] + __slots__ = ["key", "names", "types"] + @staticmethod def parse(recipe_node): rmd = Recipe() - rmd.key = recipe_node.get('key') - rmd.names = [f.get('name') for f in recipe_node.findall('field')] - rmd.types = [f.get('type') for f in recipe_node.findall('field')] + rmd.key = recipe_node.get("key") + rmd.names = [f.get("name") for f in recipe_node.findall("field")] + rmd.types = [f.get("type") for f in recipe_node.findall("field")] return rmd @@ -40,11 +41,11 @@ def __init__(self, filename): self.__filename = filename tree = ET.parse(self.__filename) root = tree.getroot() - recipes = [Recipe.parse(r) for r in root.findall('recipe')] + recipes = [Recipe.parse(r) for r in root.findall("recipe")] self.__dictionary = dict() for r in recipes: self.__dictionary[r.key] = r - + def get_recipe(self, key): r = self.__dictionary[key] return r.names, r.types diff --git a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/serialize.py b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/serialize.py index a536c53b..f6c86930 100644 --- a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/serialize.py +++ b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/rtde/serialize.py @@ -25,54 +25,57 @@ class ControlHeader(object): - __slots__ = ['command', 'size',] - + __slots__ = [ + "command", + "size", + ] + @staticmethod def unpack(buf): rmd = ControlHeader() - (rmd.size, rmd.command) = struct.unpack_from('>HB', buf) + (rmd.size, rmd.command) = struct.unpack_from(">HB", buf) return rmd class ControlVersion(object): - __slots__ = ['major', 'minor', 'bugfix', 'build'] - + __slots__ = ["major", "minor", "bugfix", "build"] + @staticmethod def unpack(buf): rmd = ControlVersion() - (rmd.major, rmd.minor, rmd.bugfix, rmd.build) = struct.unpack_from('>IIII', buf) + (rmd.major, rmd.minor, rmd.bugfix, rmd.build) = struct.unpack_from(">IIII", buf) return rmd class ReturnValue(object): - __slots__ = ['success'] - + __slots__ = ["success"] + @staticmethod def unpack(buf): rmd = ReturnValue() - rmd.success = bool(struct.unpack_from('>B', buf)[0]) + rmd.success = bool(struct.unpack_from(">B", buf)[0]) return rmd class Message(object): - __slots__ = ['level', 'message', 'source'] + __slots__ = ["level", "message", "source"] EXCEPTION_MESSAGE = 0 ERROR_MESSAGE = 1 WARNING_MESSAGE = 2 INFO_MESSAGE = 3 - + @staticmethod def unpack(buf): rmd = Message() offset = 0 msg_length = struct.unpack_from(">B", buf, offset)[0] offset = offset + 1 - rmd.message = buf[offset:offset+msg_length] + rmd.message = buf[offset : offset + msg_length] offset = offset + msg_length src_length = struct.unpack_from(">B", buf, offset)[0] offset = offset + 1 - rmd.source = buf[offset:offset+src_length] + rmd.source = buf[offset : offset + src_length] offset = offset + src_length rmd.level = struct.unpack_from(">B", buf, offset)[0] @@ -80,55 +83,54 @@ def unpack(buf): def get_item_size(data_type): - if data_type.startswith('VECTOR6'): + if data_type.startswith("VECTOR6"): return 6 - elif data_type.startswith('VECTOR3'): + elif data_type.startswith("VECTOR3"): return 3 return 1 + def unpack_field(data, offset, data_type): size = get_item_size(data_type) - if(data_type == 'VECTOR6D' or - data_type == 'VECTOR3D'): - return [float(data[offset+i]) for i in range(size)] - elif(data_type == 'VECTOR6UINT32'): - return [int(data[offset+i]) for i in range(size)] - elif(data_type == 'DOUBLE'): + if data_type == "VECTOR6D" or data_type == "VECTOR3D": + return [float(data[offset + i]) for i in range(size)] + elif data_type == "VECTOR6UINT32": + return [int(data[offset + i]) for i in range(size)] + elif data_type == "DOUBLE": return float(data[offset]) - elif(data_type == 'UINT32' or - data_type == 'UINT64'): + elif data_type == "UINT32" or data_type == "UINT64": return int(data[offset]) - elif(data_type == 'VECTOR6INT32'): - return [int(data[offset+i]) for i in range(size)] - elif(data_type == 'INT32' or - data_type == 'UINT8'): + elif data_type == "VECTOR6INT32": + return [int(data[offset + i]) for i in range(size)] + elif data_type == "INT32" or data_type == "UINT8": return int(data[offset]) - elif(data_type == 'BOOL'): + elif data_type == "BOOL": return bool(data[offset]) - raise ValueError('unpack_field: unknown data type: ' + data_type) + raise ValueError("unpack_field: unknown data type: " + data_type) class DataObject(object): recipe_id = None + def pack(self, names, types): if len(names) != len(types): - raise ValueError('List sizes are not identical.') + raise ValueError("List sizes are not identical.") l = [] - if(self.recipe_id is not None): + if self.recipe_id is not None: l.append(self.recipe_id) for i in range(len(names)): if self.__dict__[names[i]] is None: - raise ValueError('Uninitialized parameter: ' + names[i]) - if types[i].startswith('VECTOR'): + raise ValueError("Uninitialized parameter: " + names[i]) + if types[i].startswith("VECTOR"): l.extend(self.__dict__[names[i]]) else: l.append(self.__dict__[names[i]]) return l - + @staticmethod def unpack(data, names, types): if len(names) != len(types): - raise ValueError('List sizes are not identical.') + raise ValueError("List sizes are not identical.") obj = DataObject() offset = 0 obj.recipe_id = data[0] @@ -147,45 +149,45 @@ def create_empty(names, recipe_id): class DataConfig(object): - __slots__ = ['id', 'names', 'types', 'fmt'] + __slots__ = ["id", "names", "types", "fmt"] + @staticmethod def unpack_recipe(buf): - rmd = DataConfig(); - rmd.id = struct.unpack_from('>B', buf)[0] - rmd.types = buf.decode('utf-8')[1:].split(',') - rmd.fmt = '>B' + rmd = DataConfig() + rmd.id = struct.unpack_from(">B", buf)[0] + rmd.types = buf.decode("utf-8")[1:].split(",") + rmd.fmt = ">B" for i in rmd.types: - if i=='INT32': - rmd.fmt += 'i' - elif i=='UINT32': - rmd.fmt += 'I' - elif i=='VECTOR6D': - rmd.fmt += 'd'*6 - elif i=='VECTOR3D': - rmd.fmt += 'd'*3 - elif i=='VECTOR6INT32': - rmd.fmt += 'i'*6 - elif i=='VECTOR6UINT32': - rmd.fmt += 'I'*6 - elif i=='DOUBLE': - rmd.fmt += 'd' - elif i=='UINT64': - rmd.fmt += 'Q' - elif i=='UINT8': - rmd.fmt += 'B' - elif i =='BOOL': - rmd.fmt += '?' - elif i=='IN_USE': - raise ValueError('An input parameter is already in use.') + if i == "INT32": + rmd.fmt += "i" + elif i == "UINT32": + rmd.fmt += "I" + elif i == "VECTOR6D": + rmd.fmt += "d" * 6 + elif i == "VECTOR3D": + rmd.fmt += "d" * 3 + elif i == "VECTOR6INT32": + rmd.fmt += "i" * 6 + elif i == "VECTOR6UINT32": + rmd.fmt += "I" * 6 + elif i == "DOUBLE": + rmd.fmt += "d" + elif i == "UINT64": + rmd.fmt += "Q" + elif i == "UINT8": + rmd.fmt += "B" + elif i == "BOOL": + rmd.fmt += "?" + elif i == "IN_USE": + raise ValueError("An input parameter is already in use.") else: - raise ValueError('Unknown data type: ' + i) + raise ValueError("Unknown data type: " + i) return rmd - + def pack(self, state): l = state.pack(self.names, self.types) return struct.pack(self.fmt, *l) def unpack(self, data): - li = struct.unpack_from(self.fmt, data) + li = struct.unpack_from(self.fmt, data) return DataObject.unpack(li, self.names, self.types) - diff --git a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/universal_robots_perform_hand_eye_calibration.py b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/universal_robots_perform_hand_eye_calibration.py index b78c75eb..73dcbc01 100644 --- a/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/universal_robots_perform_hand_eye_calibration.py +++ b/source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/universal_robots_perform_hand_eye_calibration.py @@ -37,20 +37,14 @@ def _options(): """ parser = argparse.ArgumentParser(description=__doc__) mode_group = parser.add_mutually_exclusive_group(required=True) - mode_group.add_argument( - "--eih", "--eye-in-hand", action="store_true", help="eye-in-hand calibration" - ) - mode_group.add_argument( - "--eth", "--eye-to-hand", action="store_true", help="eye-to-hand calibration" - ) + mode_group.add_argument("--eih", "--eye-in-hand", action="store_true", help="eye-in-hand calibration") + mode_group.add_argument("--eth", "--eye-to-hand", action="store_true", help="eye-to-hand calibration") parser.add_argument("--ip", required=True, help="IP address to robot") return parser.parse_args() -def _write_robot_state( - con: rtde, input_data, finish_capture: bool = False, camera_ready: bool = False -): +def _write_robot_state(con: rtde, input_data, finish_capture: bool = False, camera_ready: bool = False): """Write to robot I/O registrer Args: @@ -107,9 +101,7 @@ def _initialize_robot_sync(host: str): return con, robot_input_data -def _save_zdf_and_pose( - save_dir: Path, image_num: int, frame: zivid.Frame, transform: np.array -): +def _save_zdf_and_pose(save_dir: Path, image_num: int, frame: zivid.Frame, transform: np.array): """Save data to folder Args: @@ -121,9 +113,7 @@ def _save_zdf_and_pose( frame.save(save_dir / f"img{image_num:02d}.zdf") - file_storage = cv2.FileStorage( - str(save_dir / f"pos{image_num:02d}.yaml"), cv2.FILE_STORAGE_WRITE - ) + file_storage = cv2.FileStorage(str(save_dir / f"pos{image_num:02d}.yaml"), cv2.FILE_STORAGE_WRITE) file_storage.write("PoseState", transform) file_storage.release() @@ -135,9 +125,7 @@ def _generate_folder(): Directory to where data will be saved """ - location_dir = ( - Path.cwd() / "datasets" / datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") - ) + location_dir = Path.cwd() / "datasets" / datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if not location_dir.is_dir(): location_dir.mkdir(parents=True) @@ -213,9 +201,7 @@ def pose_from_datastring(datastring: str): """ string = datastring.split("data:")[-1].strip().strip("[").strip("]") - pose_matrix = np.fromstring(string, dtype=np.float, count=16, sep=",").reshape( - (4, 4) - ) + pose_matrix = np.fromstring(string, dtype=np.float, count=16, sep=",").reshape((4, 4)) return zivid.hand_eye.Pose(pose_matrix) @@ -228,15 +214,11 @@ def _save_hand_eye_results(save_dir: Path, transform: np.array, residuals: list) residuals: List of residuals """ - file_storage_transform = cv2.FileStorage( - str(save_dir / "transformation.yaml"), cv2.FILE_STORAGE_WRITE - ) + file_storage_transform = cv2.FileStorage(str(save_dir / "transformation.yaml"), cv2.FILE_STORAGE_WRITE) file_storage_transform.write("PoseState", transform) file_storage_transform.release() - file_storage_residuals = cv2.FileStorage( - str(save_dir / "residuals.yaml"), cv2.FILE_STORAGE_WRITE - ) + file_storage_residuals = cv2.FileStorage(str(save_dir / "residuals.yaml"), cv2.FILE_STORAGE_WRITE) residual_list = [] for res in residuals: tmp = list([res.translation, res.translation]) @@ -314,13 +296,9 @@ def _capture_one_frame_and_robot_pose( _verify_good_capture(frame) # Signal robot to move to next position, then set signal to low again. - _write_robot_state( - con, input_data, finish_capture=True, camera_ready=ready_to_capture - ) + _write_robot_state(con, input_data, finish_capture=True, camera_ready=ready_to_capture) time.sleep(0.1) - _write_robot_state( - con, input_data, finish_capture=False, camera_ready=ready_to_capture - ) + _write_robot_state(con, input_data, finish_capture=False, camera_ready=ready_to_capture) _save_zdf_and_pose(save_dir, image_num, frame, transform) print("Image and pose saved") @@ -344,9 +322,7 @@ def _generate_dataset(con: rtde, input_data): # Signal robot that camera is ready ready_to_capture = True - _write_robot_state( - con, input_data, finish_capture=False, camera_ready=ready_to_capture - ) + _write_robot_state(con, input_data, finish_capture=False, camera_ready=ready_to_capture) robot_state = _read_robot_state(con) @@ -360,9 +336,7 @@ def _generate_dataset(con: rtde, input_data): while _image_count(robot_state) != -1: robot_state = _read_robot_state(con) - if _ready_for_capture(robot_state) and images_captured == _image_count( - robot_state - ): + if _ready_for_capture(robot_state) and images_captured == _image_count(robot_state): print(f"Capture image {_image_count(robot_state)}") _capture_one_frame_and_robot_pose( con, @@ -417,9 +391,7 @@ def perform_hand_eye_calibration(mode: str, data_dir: Path): detected_features = zivid.hand_eye.detect_feature_points(point_cloud) if not detected_features: - raise RuntimeError( - f"Failed to detect feature points from frame {frame_file}" - ) + raise RuntimeError(f"Failed to detect feature points from frame {frame_file}") print(f"Read robot pose from pos{idata:02d}.yaml") with open(pose_file) as file: diff --git a/source/applications/advanced/hand_eye_calibration/utilize_eye_in_hand_calibration.py b/source/applications/advanced/hand_eye_calibration/utilize_eye_in_hand_calibration.py index ee901b98..2731fd35 100644 --- a/source/applications/advanced/hand_eye_calibration/utilize_eye_in_hand_calibration.py +++ b/source/applications/advanced/hand_eye_calibration/utilize_eye_in_hand_calibration.py @@ -35,9 +35,7 @@ def _assert_valid_matrix(file_name): shape = pose_state_node.mat().shape if shape[0] != 4 or shape[1] != 4: file_storage.release() - raise ValueError( - f"Expected 4x4 matrix in {file_name}, but got {shape[0]} x {shape[1]}" - ) + raise ValueError(f"Expected 4x4 matrix in {file_name}, but got {shape[0]} x {shape[1]}") def _read_transform(file_name): @@ -68,12 +66,8 @@ def _main(): print(f"Point coordinates in camera frame: {point_in_camera_frame[0:3]}") # Check if YAML files are valid - eye_in_hand_transform_file = str( - Path(f"{str(zivid.environment.data_path())}/EyeInHandTransform.yaml") - ) - robot_transform_file = str( - Path(f"{str(zivid.environment.data_path())}/RobotTransform.yaml") - ) + eye_in_hand_transform_file = str(Path(f"{str(zivid.environment.data_path())}/EyeInHandTransform.yaml")) + robot_transform_file = str(Path(f"{str(zivid.environment.data_path())}/RobotTransform.yaml")) _assert_valid_matrix(eye_in_hand_transform_file) _assert_valid_matrix(robot_transform_file) @@ -84,9 +78,7 @@ def _main(): transform_base_to_end_effector = _read_transform(robot_transform_file) # Computing camera pose in robot base frame - transform_base_to_camera = np.matmul( - transform_base_to_end_effector, transform_end_effector_to_camera - ) + transform_base_to_camera = np.matmul(transform_base_to_end_effector, transform_end_effector_to_camera) # Computing (picking) point in robot base frame point_in_base_frame = np.matmul(transform_base_to_camera, point_in_camera_frame) diff --git a/source/applications/advanced/mask_point_cloud.py b/source/applications/advanced/mask_point_cloud.py index b6b16bb3..6cf5cdff 100644 --- a/source/applications/advanced/mask_point_cloud.py +++ b/source/applications/advanced/mask_point_cloud.py @@ -100,9 +100,7 @@ def _main(): rgb = np.dstack([point_cloud["r"], point_cloud["g"], point_cloud["b"]]) pixels_to_display = 300 - print( - f"Generating a binary mask of central {pixels_to_display} x {pixels_to_display} pixels" - ) + print(f"Generating a binary mask of central {pixels_to_display} x {pixels_to_display} pixels") mask = np.zeros((rgb.shape[0], rgb.shape[1]), np.bool) height = frame.get_point_cloud().height width = frame.get_point_cloud().width diff --git a/source/applications/basic/capture_hdr_loop.py b/source/applications/basic/capture_hdr_loop.py index 0bf86ec0..d50a5664 100644 --- a/source/applications/basic/capture_hdr_loop.py +++ b/source/applications/basic/capture_hdr_loop.py @@ -16,9 +16,7 @@ def _read_settings_from_file(path: Path) -> zivid.Settings: settings_from_yaml = yaml.load(path.read_text(), Loader=yaml.Loader)["Settings"] settings = zivid.Settings( brightness=settings_from_yaml["Brightness"], - exposure_time=datetime.timedelta( - microseconds=settings_from_yaml["ExposureTime"] - ), + exposure_time=datetime.timedelta(microseconds=settings_from_yaml["ExposureTime"]), gain=settings_from_yaml["Gain"], iris=settings_from_yaml["Iris"], ) @@ -48,8 +46,7 @@ def _main(): settingslist = [] for frame_index in range(number_of_frames_per_hdr): settings = _read_settings_from_file( - Path() - / f"{str(zivid.environment.data_path())}/Settings/Set{hdr_index+1}/Frame0{frame_index+1}.yml" + Path() / f"{str(zivid.environment.data_path())}/Settings/Set{hdr_index+1}/Frame0{frame_index+1}.yml" ) print( f"\tFrame {frame_index + 1}:" diff --git a/source/applications/basic/file_formats/convert_zdf.py b/source/applications/basic/file_formats/convert_zdf.py index 5e79dc32..20f57c53 100644 --- a/source/applications/basic/file_formats/convert_zdf.py +++ b/source/applications/basic/file_formats/convert_zdf.py @@ -34,9 +34,7 @@ def _options(): action="store_true", help="Convert to Portable Network Graphics (3D->2D)", ) - group.add_argument( - "--bmp", action="store_true", help="Convert to Windows bitmap (3D->2D)" - ) + group.add_argument("--bmp", action="store_true", help="Convert to Windows bitmap (3D->2D)") return parser.parse_args() diff --git a/source/applications/basic/file_formats/read_iterate_zdf.py b/source/applications/basic/file_formats/read_iterate_zdf.py index a2dd2327..04f720b1 100644 --- a/source/applications/basic/file_formats/read_iterate_zdf.py +++ b/source/applications/basic/file_formats/read_iterate_zdf.py @@ -33,12 +33,8 @@ def _main(): # Iterating over the point cloud and displaying X, Y, Z, R, G, B, and Contrast # for central 10 x 10 pixels pixels_to_display = 10 - for i in range( - int((height - pixels_to_display) / 2), int((height + pixels_to_display) / 2) - ): - for j in range( - int((width - pixels_to_display) / 2), int((width + pixels_to_display) / 2) - ): + for i in range(int((height - pixels_to_display) / 2), int((height + pixels_to_display) / 2)): + for j in range(int((width - pixels_to_display) / 2), int((width + pixels_to_display) / 2)): print( f"Values at pixel ({i} , {j}): X:{xyz[i,j,0]:.1f} Y:{xyz[i,j,1]:.1f}" f"Z:{xyz[i,j,2]:.1f} R:{rgb[i,j,0]} G:{rgb[i,j,1]} B:{rgb[i,j,2]}" diff --git a/source/applications/basic/file_formats/zdf_2_csv_without_zivid.py b/source/applications/basic/file_formats/zdf_2_csv_without_zivid.py index 06a06fa8..1d6af6f4 100644 --- a/source/applications/basic/file_formats/zdf_2_csv_without_zivid.py +++ b/source/applications/basic/file_formats/zdf_2_csv_without_zivid.py @@ -34,9 +34,7 @@ def _main(): # flattened_point_cloud = point_cloud.reshape(-1,3) # Removing nans - flattened_point_cloud = flattened_point_cloud[ - ~np.isnan(flattened_point_cloud[:, 0]), : - ] + flattened_point_cloud = flattened_point_cloud[~np.isnan(flattened_point_cloud[:, 0]), :] print(f"Saving the frame to {filename_csv}") np.savetxt(filename_csv, flattened_point_cloud, delimiter=",", fmt="%.3f") diff --git a/source/applications/basic/file_formats/zdf_2_txt_without_zivid.py b/source/applications/basic/file_formats/zdf_2_txt_without_zivid.py index 53fe6c36..8356951e 100644 --- a/source/applications/basic/file_formats/zdf_2_txt_without_zivid.py +++ b/source/applications/basic/file_formats/zdf_2_txt_without_zivid.py @@ -34,9 +34,7 @@ def _main(): # flattened_point_cloud = pc.reshape(-1,3) # Removing nans - flattened_point_cloud = flattened_point_cloud[ - ~np.isnan(flattened_point_cloud[:, 0]), : - ] + flattened_point_cloud = flattened_point_cloud[~np.isnan(flattened_point_cloud[:, 0]), :] print(f"Saving the frame to {filename_txt}") np.savetxt(filename_txt, flattened_point_cloud, delimiter=" ", fmt="%.3f") diff --git a/source/camera/basic/capture_assistant.py b/source/camera/basic/capture_assistant.py index aa91e8c7..c7ad9564 100644 --- a/source/camera/basic/capture_assistant.py +++ b/source/camera/basic/capture_assistant.py @@ -13,9 +13,7 @@ def _main(): ambient_light_frequency=AmbientLightFrequency.hz50, ) - settings_list = zivid.capture_assistant.suggest_settings( - camera, suggest_settings_parameters - ) + settings_list = zivid.capture_assistant.suggest_settings(camera, suggest_settings_parameters) with zivid.hdr.capture(camera, settings_list) as hdr_frame: hdr_frame.save("Result.zdf") diff --git a/source/camera/basic/capture_from_file.py b/source/camera/basic/capture_from_file.py index fece1a62..df8fc608 100644 --- a/source/camera/basic/capture_from_file.py +++ b/source/camera/basic/capture_from_file.py @@ -4,9 +4,7 @@ def _main(): app = zivid.Application() - camera = app.create_file_camera( - str(zivid.environment.data_path()) + "/MiscObjects.zdf" - ) + camera = app.create_file_camera(str(zivid.environment.data_path()) + "/MiscObjects.zdf") with camera.capture() as frame: frame.save("Result.zdf") diff --git a/source/camera/basic/capture_hdr_complete_settings.py b/source/camera/basic/capture_hdr_complete_settings.py index 0bd454cf..b1c2eb74 100644 --- a/source/camera/basic/capture_hdr_complete_settings.py +++ b/source/camera/basic/capture_hdr_complete_settings.py @@ -23,9 +23,7 @@ def _main(): settings_collection = [camera.settings for _ in range(3)] for i in range(len(settings_collection)): settings_collection[i].iris = iris_setting[i] - settings_collection[i].exposure_time = datetime.timedelta( - microseconds=exposure_setting[i] - ) + settings_collection[i].exposure_time = datetime.timedelta(microseconds=exposure_setting[i]) settings_collection[i].brightness = 1 settings_collection[i].gain = gain_setting[i] settings_collection[i].bidirectional = 0