This repository has been archived by the owner on Mar 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
get_gcp_uvcoords.py
executable file
·225 lines (196 loc) · 6.65 KB
/
get_gcp_uvcoords.py
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
#------------------------------------------------------------------------
#------------------------------------------------------------------------
#
#
# SCRIPT : get_gcp_coords.py
# POURPOSE : Get GCP coordinates from a image based on mouse click.
# AUTHOR : Caio Eadi Stringari
# EMAIL : [email protected]
#
# V1.0 : 01/08/2016 [Caio Stringari]
# V1.1 : 16/11/2017 [Caio Stringari]
#
#------------------------------------------------------------------------
#------------------------------------------------------------------------
# system
import os
import sys
# Arguments
import argparse
# Files
from glob import glob
# numpy
import numpy as np
# image processing
import cv2
import skimage.io
# Matplotlib
import matplotlib.pyplot as plt
# I/O
from pandas import DataFrame
from pywavelearning.image import camera_parser
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
# print 'x = %d, y = %d'%(
# ix, iy)
# assign global variable to access outside of function
global coords
coords.append((ix, iy))
# Disconnect after 6 clicks
if len(coords) == ngcps:
fig.canvas.mpl_disconnect(cid)
plt.close(1)
return
if __name__ == '__main__':
print ("\nExtracting UV GCP Coordinates\n")
### Argument parser
parser = argparse.ArgumentParser()
# Add an argument to pass one good frame with the GCPS.
parser.add_argument('--input','-i',
nargs = 1,
action = 'store',
dest = 'input',
help = "Filename or folder with frames with a good view of the GCPs.",
required = True)
# Camera matrix
parser.add_argument('--camera-matrix','-cm',
nargs = 1,
action = 'store',
dest = 'camera',
required = False,
help = "Camera matrix file. Only used if undistort is True. Please use calibrate.py to generate a valid file.",)
# Mumber of GPCS to consider
parser.add_argument('--gcps','-n',
nargs = 1,
action = 'store',
dest = 'gcps',
help = "Number of GCPs that can be viewd in a single frame.",
required = True)
# output file
parser.add_argument('--output','-o',
nargs = 1,
action = 'store',
dest = 'output',
help = "Output filename (CSV encoding).",
required = True)
# output file
parser.add_argument('--show-result','--show','-show',"-s","--s",
action = 'store_true',
dest = 'show_result',
help = "Show the final result.",
required = False)
# Parser
args = parser.parse_args()
# can't use "def main():" for this script, it does not work with on_click() =[
# files and Folders
isfolder = os.path.isdir(args.input[0])
if isfolder:
files =sorted(glob(args.input[0]+"/*.jpg"))
if not files:
raise IOError("There is no jpgs in {}".format(args.input[0]))
else:
jpg = args.input[0]
# number of GCPS
ngcps = int(args.gcps[0])
# camera matrix
cm = args.camera[0]
if os.path.isfile(cm):
K,DC = camera_parser(cm)
else:
raise IOError("Cannot fint the camera-matrix file.")
# folder case
if isfolder:
# intiate
U = []
V = []
for jpg in files:
coords = []
# read the frame
I = skimage.io.imread(jpg)
h, w = I.shape[:2]
# if undistort is true, undistort
Kn,roi = cv2.getOptimalNewCameraMatrix(K,DC,(w,h),1,(w,h))
I = cv2.undistort(I, K, DC, None, Kn)
# Start GUI
fig,ax = plt.subplots(figsize=(20,20))
ax.set_aspect('equal')
skimage.io.imshow(I,ax=ax)
# call click func
cid = fig.canvas.mpl_connect('button_press_event', onclick)
# show the figure
plt.show()
plt.close()
# append to output
U.append(coords[0][0])
V.append(coords[0][1])
# output
U = np.array(U).astype(int)
V = np.array(V).astype(int)
df = DataFrame(np.vstack([U,V]).T.astype(int),columns=["u","v"])
# update names in the same order as the clicks
gcps = []
for i in range(len(df.index.values)):
gcps.append("GCP {}".format(str(i+1).zfill(2)))
# updated dataframe
df.index = gcps
df.index.name = "GCPs"
# print the dataframe on screen
print ("\n")
print (df)
# dump to .csv
df.to_csv(args.output[0])
# single image case
else:
coords = []
# read the frame
I = skimage.io.imread(jpg)
h, w = I.shape[:2]
# undistort
Kn,roi = cv2.getOptimalNewCameraMatrix(K,DC,(w,h),1,(w,h))
I = cv2.undistort(I, K, DC, None, Kn)
# start GUI
fig,ax = plt.subplots(figsize=(20,20))
ax.set_aspect('equal')
skimage.io.imshow(I,ax=ax)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
# show the figure
plt.show()
# GCP names
gcps=[]
for k in np.arange(len(coords))+1:
gcps.append("GCP {}".format(str(k).zfill(2)))
# create a dataframe
df = DataFrame(np.array(coords).astype(int),columns=["u","v"])
df.index = gcps
df.index.name = "GCPs"
# # update names in the same order as the clicks
gcps = []
for i in range(len(df.index.values)):
gcps.append("GCP {}".format(str(i+1).zfill(2)))
# updated dataframe
df.index = gcps
df.index.name = "GCPs"
print ('\n')
print (df)
# dump to csv
df.to_csv(args.output[0])
# plot the final result
if args.show_result:
fig,ax = plt.subplots(figsize=(20,20))
ax.set_aspect('equal')
skimage.io.imshow(I)
# scatter the GCPS
plt.scatter(df.u.values,df.v.values,s=40,c="r",marker="+",linewidths=2)
# plot the GCPS names
for x,y,gcp in zip(df.u.values,df.v.values,gcps):
t = plt.text(x+30,y,gcp,color="k",fontsize=10)
t.set_bbox(dict(facecolor=".5",edgecolor="k",alpha=0.85,linewidth=1))
# set axes
plt.ylim(I.shape[0],0)
plt.xlim(0,I.shape[1])
plt.tight_layout
# show the plot
plt.show()
plt.close()
print ("\nMy work is done!\n")