python文件讀寫與序列化

 

 1 import os
 2 import pickle
 3 import numpy as np
 4 import cv2
 5 import scipy.io as sio
 6 from tqdm import tqdm
 7 
 8 data_root = 'D:/dl_exp/Labeling_lines/linefeature_2'
 9 data_img_path = data_root + '/photo'
10 data_path= 'dataOwn'
11 
12 data_anno_list = data_img_path + '/anno_shp.txt'
13 
14 outPath = data_path + '/dataset'
15 
16 if not os.path.exists(outPath):
17     os.makedirs(outPath)
18 
19 imgnames=[]
20 with open(data_anno_list, 'r') as file_to_read:
21     while True:
22         str = file_to_read.readline() # 整行讀取數據
23         if not str:
24             break
25         imgnames.append(str[:-1])
26 print(imgnames)
27 for img_name in imgnames:
28     img_file =  data_img_path + '/{}{}'.format(img_name, '.tif')
29     f_Points = data_path + '/{}{}'.format(img_name,'_Points.txt' )
30     f_Edges = data_path + '/{}{}'.format(img_name,'_Edge.txt' )
31     f_Funcs = data_path + '/{}{}'.format(img_name,'_Junctions.txt')
32     ids = []
33     xys = []
34     edges = []
35     img = cv2.imread(img_file)
36     #讀取座標點
37     with open(f_Points, 'r') as file_to_read:
38         while True:
39             lines = file_to_read.readline() # 整行讀取數據
40             if not lines:
41                 break
42             id, p_x, p_y = [float(i) for i in lines.split(',')] # 將整行數據分割處理,如果分割符
43             ids.append(id) # 添加新讀取的數據
44             xys.append((p_x,p_y))
45         #ids = np.array(ids) # 將數據從list類型轉換爲array類型。
46         #xys = np.array(xys)
47     print (xys)
48     #讀取線索引
49     with open(f_Edges, 'r') as file_to_read:
50         while True:
51             texts = file_to_read.readline() # 整行讀取數據
52             if not texts:
53                 break
54             id, line_i, line_j = [float(i) for i in texts.split(',')] # 將整行數據分割處理,如果分割符
55             edges.append((line_i, line_j))
56        # edges = np.array(edges)
57     #讀取角點和角度
58     junctions = []
59     thetas = []
60     with open(f_Funcs, 'r') as file_to_read:
61         while True:
62             texts = file_to_read.readline() # 整行讀取數據
63             if not texts:
64                 break
65             id, p_x1, p_y1, n_theta = [float(i) for i in texts.split(',')] # 將整行數據分割處理
66             junc = (p_x1, p_y1)
67             junctions.append(junc)
68             ths = []
69             for _ in range(int(n_theta)):
70                 text_theta = file_to_read.readline()
71                 t = (float(text_theta), float(text_theta))
72                 ths.append(t)#每個角點多個線方向
73             #ths = np.array(ths)
74             thetas.append(ths)
75         #junctions = np.array(junctions)
76         #thetas = np.array(thetas)
77     H = {}
78     H['imagename'] = img_name
79     point=[]
80     #讀取座標點
81     for x, y in xys:
82         point.append((x,y))
83     H['points'] = point
84     lines=[]
85     #讀取線索引
86     for line_i, line_j in edges:
87         lines.append((int(line_i), int(line_j)))
88     #讀取角點
89 
90     H['lines'] = lines
91     H['junction'] = junctions
92     H['theta'] = thetas
93     H['img'] = img
94     with open(outPath + '/{}{}'.format(img_name,'.pkl'), "wb") as f:
95         pickle.dump(H, f)

 

 1 import pickle
 2 from math import cos, pi, sin, sqrt, acos
 3 import numpy as np
 4 import cv2
 5 #00030077.pkl
 6 #H.pkl
 7 #Z_4_20_DOM
 8 data_path= 'dataOwn'
 9 outPath = data_path + '/dataset'
10 pkl_file = outPath + '/{}{}'.format('Zurich_7_37_DOM','.pkl')
11 with open(pkl_file, 'rb') as handle:
12     target = pickle.load(handle, encoding='latin1')
13     #print(target)
14 
15     junction = target['junction']
16     theta = target['theta']
17     points = target['points']
18     lines = target['lines']
19     print("角點")
20     print(junction)
21     print("射線角度")
22     print(theta)
23     print("座標點")
24     print(points)
25     print("")
26     print(lines)
27     new_ths = [None for _ in theta]
28     img=target['img']
29     cur_h, cur_w = img.shape[:2]
30     sw = float(cur_w)
31     sh = float(cur_h)
32     scale_param = (sw, sh)
33     theta= [[x for x, _ in th] for th in target['theta']]
34     for cnt0, th in enumerate(theta):
35         bin_t = [None for _ in th]
36         for cnt, t in enumerate(th):
37             x = cos(t * pi / 180.) * scale_param[0]
38             y = sin(t * pi / 180.) * scale_param[1]
39             dist = sqrt(x ** 2 + y ** 2)
40             if abs(y) <= 0.001:
41                 nt = 180. if x < 0 else 0.
42             elif y > 0:
43                 nt = acos(x / dist) / pi * 180.
44             else:
45                 nt = 360. - acos(x / dist) / pi * 180.
46             bin_t[cnt] = nt
47             print("處理後:")
48             print(bin_t)
49 
50     junction_color = (0, 0, 255)
51     line_color = (0, 255, 0)
52     line_length = 12
53     nimage = np.zeros((cur_h,cur_w ,3), np.uint8)
54     #cv2.resize(nimage, (origin_w, origin_h))
55     w, h = cur_w, cur_h
56     for idx, (jx, jy) in enumerate(junction):
57         if not ((jx >= 0 and jx <= w) and (jy >= 0 and jy <= h)):
58             continue
59         try:
60             cv2.circle(nimage, (int(jx), int(jy)), 2, junction_color, -1)
61         except OverflowError:
62             print(jx, jy)
63             raise
64         # 繪製角點的方向線?????
65         for th in theta[idx]:
66             rad = th * pi / 180.0
67             dx, dy = (cos(rad), sin(rad))
68             xe, ye = (jx + line_length * dx, jy + line_length * dy)
69             xe, ye = min(max(xe, 0), w), min(max(ye, 0), h)
70             print("line: {},{}  {},{}".format(jx, jy, xe, ye))
71             cv2.line(nimage, (int(jx), int(jy)), (int(xe), int(ye)), line_color, 2)
72     cv2.imshow('img', nimage)
73     cv2.waitKey(0)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章