-
Notifications
You must be signed in to change notification settings - Fork 0
/
opencv2imagej.rb
executable file
·55 lines (46 loc) · 1.63 KB
/
opencv2imagej.rb
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
#!/usr/bin/env ruby
#
# Converts a YAML file generated by OpenCV's FileStorage interface into a format that can be imported by ImageJ.
# OpenCV YAML file format: http://docs.opencv.org/2.4/modules/core/doc/xml_yaml_persistence.html#filestorage
# ImageJ Text Image file format: https://imagej.nih.gov/ij/docs/guide/146-26.html#fig:TextImages
#
require 'yaml'
def convert_file(image_key, infile, outfile)
# Ruby's yaml parser can't parse the YAML 1.0 directive "%YAML:1.0"
# So we can't just use YAML.load_file(infile)
# http://stackoverflow.com/questions/17560350/cannot-parse-yaml1-0-in-ruby
contents = IO.read(infile)
contents.gsub!(/%/, '#%')
contents = YAML.load(contents)
rows = contents[image_key]['rows']
cols = contents[image_key]['cols']
data = contents[image_key]['data']
File.open(outfile, 'w') do |file|
for r in 0..(rows -1)
for c in 0..(cols -1)
file.write(data[r * cols + c])
file.write("\t") unless c == (cols - 1)
end
file.write("\n")
end
end
end
def get_outfile(infile)
infile.chomp(File.extname(infile)) + '.txt'
end
if ARGV.size == 0
puts 'Usage: ruby ./opencv2imagej.rb yaml-file-or-directory-of-yaml-files [image_key]'
puts 'yaml_file: path to an OpenCV image in yaml format'
puts 'image_key: the name of the serialized image, default is "img"'
exit
end
image_key = ARGV[1] || 'img'
infile = ARGV[0]
if File.directory?(infile)
infile += File::SEPARATOR unless infile.end_with?(File::SEPARATOR)
Dir.glob(infile + '*.yml') do |filename|
convert_file(image_key, filename, get_outfile(filename))
end
else
convert_file(image_key, infile, get_outfile(infile))
end