Python读取xyz坐标文件输出csv文件
import sys
import numpy as np
import pandas as pd
from tqdm import tqdm
import cv2
import argparsedef read_xyz ( file_path) : with open ( file_path, "r" ) as f: data = f. readlines( ) datas = [ ] for i in tqdm( data[ 7 : 8 ] ) : i_split = i. split( ' ' ) eta= float ( i_split[ 6 ] ) for i in tqdm( data[ 14 : - 1 ] ) : i_split = i. split( ' ' ) x = int ( i_split[ 0 ] ) y = int ( i_split[ 1 ] ) try : z = float ( i_split[ 2 ] . split( '\n' ) [ 0 ] ) except ValueError: z = 0 datas. append( [ x, y, z] ) return datas, etadef convert_cv_mat ( data, vis= False ) : data_mat = np. ones( shape= [ 1024 , 1024 , 1 ] , dtype= np. uint8) for i in data: if i[ 2 ] == 0 : data_mat[ i[ 0 ] , i[ 1 ] , 0 ] = 0 else : data_mat[ i[ 0 ] , i[ 1 ] , 0 ] = 255 if vis: cv2. imshow( 'data_mat' , data_mat) cv2. waitKey( 1000 ) cv2. destroyAllWindows( ) return data_matdef center ( img, vis= False ) : canny_output = cv2. Canny( img, 50 , 50 * 2 ) contours, hierarchy = cv2. findContours( canny_output, cv2. RETR_TREE, cv2. CHAIN_APPROX_SIMPLE) f_cx = 0 f_cy = 0 f_a = 0 f_b = 0 f_angle = 0 area = 0 for c in range ( len ( contours) ) : if len ( contours[ c] ) < 5 : continue ( cx, cy) , ( a, b) , angle = cv2. fitEllipse( contours[ c] ) if a * b > area: f_cx = cxf_cy = cyf_a = af_b = bf_angle = anglearea = a * bif vis: cv2. circle( img, ( np. uint16( np. around( f_cx) ) , np. uint16( np. around( f_cy) ) ) , 5 , ( 0 , 255 , 255 ) , - 1 ) cv2. putText( img, 'cx:{}, cy:{}' . format ( np. int32( f_cx) , np. int32( f_cy) ) , ( 50 , 100 ) , cv2. FONT_HERSHEY_COMPLEX, 2 , ( 0 , 0 , 255 ) , 2 ) cv2. imshow( 'img' , img) cv2. waitKey( 1000 ) cv2. destroyAllWindows( ) return np. int16( np. around( f_cy) ) , np. int16( np. around( f_cx) ) def to_csv ( data, file_name, cx= 512 , cy= 512 , eta = 8.41837e-005 ) : datas = [ ] for i in data: x = ( i[ 0 ] - cx) * eta* 1000 y = ( cy - i[ 1 ] ) * eta* 1000 z = i[ 2 ] datas. append( [ x, y, z] ) df = pd. DataFrame( datas, index= None , columns= [ 'x' , 'y' , 'z' ] ) df. to_csv( file_name+ '_data.csv' , index= None ) if __name__ == "__main__" : arguments = sys. argv[ 1 ] ; data, eta = read_xyz( arguments) data_mat = convert_cv_mat( data, vis= False ) cx, cy = center( data_mat, vis= False ) to_csv( data, arguments, cx, cy, eta)