Skip to content

Commit 8c25de7

Browse files
committed
pipes, scripts etc
1 parent 73bdb31 commit 8c25de7

14 files changed

Lines changed: 1188 additions & 113 deletions

File tree

opencvlib/imgpipes/generators.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -419,7 +419,8 @@ class FromPaths(_Generator):
419419
if none exists.
420420
421421
Example:
422-
fp = generators.FromPaths('C:/temp', wildcards='*.jpg')
422+
fp = generators.FromPaths('C:/temp', wildcards='*.jpg',
423+
transforms=Transforms, filters=Filters)
423424
'''
424425
def __init__(self, paths, *args, wildcards=_IMAGE_EXTENSIONS_AS_WILDCARDS, **kwargs):
425426
self._paths = paths

opencvlib/learning/forest.py

Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
# pylint: disable=C0103, too-few-public-methods, locally-disabled, no-self-use, unused-argument
2+
'''Implement a random forest from scratch'''
3+
4+
# Random Forest Algorithm on Sonar Dataset
5+
from random import seed
6+
from random import randrange
7+
from csv import reader
8+
from math import sqrt
9+
10+
11+
12+
13+
# Load a CSV file
14+
def load_csv(filename):
15+
dataset = list()
16+
with open(filename, 'r') as file:
17+
csv_reader = reader(file)
18+
for row in csv_reader:
19+
if not row:
20+
continue
21+
dataset.append(row)
22+
return dataset
23+
24+
25+
# Convert string column to float
26+
def str_column_to_float(dataset, column):
27+
for row in dataset:
28+
row[column] = float(row[column].strip())
29+
30+
31+
# Convert string column to integer
32+
def str_column_to_int(dataset, column):
33+
class_values = [row[column] for row in dataset]
34+
unique = set(class_values)
35+
lookup = dict()
36+
for i, value in enumerate(unique):
37+
lookup[value] = i
38+
for row in dataset:
39+
row[column] = lookup[row[column]]
40+
return lookup
41+
42+
43+
# Split a dataset into k folds
44+
def cross_validation_split(dataset, n_folds):
45+
dataset_split = list()
46+
dataset_copy = list(dataset)
47+
fold_size = int(len(dataset) / n_folds)
48+
for i in range(n_folds):
49+
fold = list()
50+
while len(fold) < fold_size:
51+
index = randrange(len(dataset_copy))
52+
fold.append(dataset_copy.pop(index))
53+
dataset_split.append(fold)
54+
return dataset_split
55+
56+
57+
# Calculate accuracy percentage
58+
def accuracy_metric(actual, predicted):
59+
correct = 0
60+
for i in range(len(actual)):
61+
if actual[i] == predicted[i]:
62+
correct += 1
63+
return correct / float(len(actual)) * 100.0
64+
65+
66+
# Evaluate an algorithm using a cross validation split
67+
def evaluate_algorithm(dataset, algorithm, n_folds, *args):
68+
folds = cross_validation_split(dataset, n_folds)
69+
scores = list()
70+
for fold in folds:
71+
train_set = list(folds)
72+
train_set.remove(fold)
73+
train_set = sum(train_set, [])
74+
test_set = list()
75+
for row in fold:
76+
row_copy = list(row)
77+
test_set.append(row_copy)
78+
row_copy[-1] = None
79+
predicted = algorithm(train_set, test_set, *args)
80+
actual = [row[-1] for row in fold]
81+
accuracy = accuracy_metric(actual, predicted)
82+
scores.append(accuracy)
83+
return scores
84+
85+
86+
# Split a dataset based on an attribute and an attribute value
87+
def test_split(index, value, dataset):
88+
left, right = list(), list()
89+
for row in dataset:
90+
if row[index] < value:
91+
left.append(row)
92+
else:
93+
right.append(row)
94+
return left, right
95+
96+
97+
# Calculate the Gini index for a split dataset
98+
def gini_index(groups, classes):
99+
# count all samples at split point
100+
n_instances = float(sum([len(group) for group in groups]))
101+
# sum weighted Gini index for each group
102+
gini = 0.0
103+
for group in groups:
104+
size = float(len(group))
105+
# avoid divide by zero
106+
if size == 0:
107+
continue
108+
score = 0.0
109+
# score the group based on the score for each class
110+
for class_val in classes:
111+
p = [row[-1] for row in group].count(class_val) / size
112+
score += p * p
113+
# weight the group score by its relative size
114+
gini += (1.0 - score) * (size / n_instances)
115+
return gini
116+
117+
118+
# Select the best split point for a dataset
119+
def get_split(dataset, n_features):
120+
class_values = list(set(row[-1] for row in dataset))
121+
b_index, b_value, b_score, b_groups = 999, 999, 999, None
122+
features = list()
123+
while len(features) < n_features:
124+
index = randrange(len(dataset[0])-1)
125+
if index not in features:
126+
features.append(index)
127+
for index in features:
128+
for row in dataset:
129+
groups = test_split(index, row[index], dataset)
130+
gini = gini_index(groups, class_values)
131+
if gini < b_score:
132+
b_index, b_value, b_score, b_groups = index, row[index], gini, groups
133+
return {'index':b_index, 'value':b_value, 'groups':b_groups}
134+
135+
136+
# Create a terminal node value
137+
def to_terminal(group):
138+
outcomes = [row[-1] for row in group]
139+
return max(set(outcomes), key=outcomes.count)
140+
141+
142+
# Create child splits for a node or make terminal
143+
def split(node, max_depth, min_size, n_features, depth):
144+
left, right = node['groups']
145+
del(node['groups'])
146+
# check for a no split
147+
if not left or not right:
148+
node['left'] = node['right'] = to_terminal(left + right)
149+
return
150+
# check for max depth
151+
if depth >= max_depth:
152+
node['left'], node['right'] = to_terminal(left), to_terminal(right)
153+
return
154+
# process left child
155+
if len(left) <= min_size:
156+
node['left'] = to_terminal(left)
157+
else:
158+
node['left'] = get_split(left, n_features)
159+
split(node['left'], max_depth, min_size, n_features, depth+1)
160+
# process right child
161+
if len(right) <= min_size:
162+
node['right'] = to_terminal(right)
163+
else:
164+
node['right'] = get_split(right, n_features)
165+
split(node['right'], max_depth, min_size, n_features, depth+1)
166+
167+
168+
# Build a decision tree
169+
def build_tree(train, max_depth, min_size, n_features):
170+
root = get_split(train, n_features)
171+
split(root, max_depth, min_size, n_features, 1)
172+
return root
173+
174+
175+
# Make a prediction with a decision tree
176+
def predict(node, row):
177+
if row[node['index']] < node['value']:
178+
if isinstance(node['left'], dict):
179+
return predict(node['left'], row)
180+
else:
181+
return node['left']
182+
else:
183+
if isinstance(node['right'], dict):
184+
return predict(node['right'], row)
185+
else:
186+
return node['right']
187+
188+
189+
# Create a random subsample from the dataset with replacement
190+
def subsample(dataset, ratio):
191+
sample = list()
192+
n_sample = round(len(dataset) * ratio)
193+
while len(sample) < n_sample:
194+
index = randrange(len(dataset))
195+
sample.append(dataset[index])
196+
return sample
197+
198+
199+
# Make a prediction with a list of bagged trees
200+
def bagging_predict(trees, row):
201+
predictions = [predict(tree, row) for tree in trees]
202+
return max(set(predictions), key=predictions.count)
203+
204+
205+
# Random Forest Algorithm
206+
def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):
207+
trees = list()
208+
for i in range(n_trees):
209+
sample = subsample(train, sample_size)
210+
tree = build_tree(sample, max_depth, min_size, n_features)
211+
trees.append(tree)
212+
predictions = [bagging_predict(trees, row) for row in test]
213+
return(predictions)
214+
215+
216+
217+
218+
219+
220+
# Test the random forest algorithm
221+
seed(2)
222+
# load and prepare data
223+
filename = r'C:\development\python\opencvlib\test\bin\learning_data\sonar.all-data.csv'
224+
dataset = load_csv(filename)
225+
# convert string attributes to integers
226+
for i in range(0, len(dataset[0])-1):
227+
str_column_to_float(dataset, i)
228+
# convert class column to integers
229+
str_column_to_int(dataset, len(dataset[0])-1)
230+
# evaluate algorithm
231+
n_folds = 5
232+
max_depth = 10
233+
min_size = 1
234+
sample_size = 1.0
235+
n_features = int(sqrt(len(dataset[0])-1))
236+
for n_trees in [1, 5, 10]:
237+
scores = evaluate_algorithm(dataset, random_forest, n_folds, max_depth, min_size, sample_size, n_trees, n_features)
238+
print('Trees: %d' % n_trees)
239+
print('Scores: %s' % scores)
240+
print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))

opencvlib/opencvlib.pyproj

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@
55
<SchemaVersion>2.0</SchemaVersion>
66
<ProjectGuid>3791c3eb-165f-4a04-83e2-956959c15823</ProjectGuid>
77
<ProjectHome>.</ProjectHome>
8-
<StartupFile>scripts_vgg\img2roi.py</StartupFile>
8+
<StartupFile>learning\forest.py</StartupFile>
99
<SearchPath>..\</SearchPath>
1010
<WorkingDirectory>.</WorkingDirectory>
1111
<OutputPath>.</OutputPath>
1212
<Name>opencvlib</Name>
1313
<RootNamespace>opencvlib</RootNamespace>
1414
<LaunchProvider>Standard Python launcher</LaunchProvider>
15-
<CommandLineArguments>-m req_new_dir -p roi "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/train/all" "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/train/roi" vgg_body.json</CommandLineArguments>
15+
<CommandLineArguments>"C:\Users\Graham Monkman\OneDrive\Documents\PHD\images\bass\fiducial\train\candidate\roi_whole\resized"</CommandLineArguments>
1616
<EnableNativeCodeDebugging>False</EnableNativeCodeDebugging>
1717
<IsWindowsApplication>False</IsWindowsApplication>
1818
<InterpreterId>{9a7a9026-48c1-4688-9d5d-e5699d47d074}</InterpreterId>
@@ -44,7 +44,9 @@ roi2img.py -m skip -p "" "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/
4444

4545
make_train.py -n 10 "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/roi/all/bass" "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/roi/all/bass_subsample"
4646

47-
dump_digikam.py -a images -t fid_overlay "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/digikam4.db" "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/train/all"</Environment>
47+
dump_digikam.py -a images -t fid_overlay "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/digikam4.db" "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/train/all"
48+
49+
average_resize -h mean "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/train/candidate/roi_whole" "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/train/candidate/roi_whole/resized"</Environment>
4850
</PropertyGroup>
4951
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
5052
<DebugSymbols>true</DebugSymbols>
@@ -72,6 +74,9 @@ dump_digikam.py -a images -t fid_overlay "C:/Users/Graham Monkman/OneDrive/Docum
7274
<SubType>Code</SubType>
7375
</Compile>
7476
<Compile Include="imgpipes\voc_utils.py" />
77+
<Compile Include="learning\forest.py">
78+
<SubType>Code</SubType>
79+
</Compile>
7580
<Compile Include="lenscorrection\fisheye.py" />
7681
<Compile Include="matcher.py">
7782
<SubType>Code</SubType>
@@ -85,9 +90,6 @@ dump_digikam.py -a images -t fid_overlay "C:/Users/Graham Monkman/OneDrive/Docum
8590
<Compile Include="scripts_streams\play.py">
8691
<SubType>Code</SubType>
8792
</Compile>
88-
<Compile Include="scripts_tensorflow\make_base_images.py">
89-
<SubType>Code</SubType>
90-
</Compile>
9193
<Compile Include="scripts_tensorflow\make_negs.py">
9294
<SubType>Code</SubType>
9395
</Compile>
@@ -107,10 +109,12 @@ dump_digikam.py -a images -t fid_overlay "C:/Users/Graham Monkman/OneDrive/Docum
107109
<Compile Include="script_augment\make_train_augmentor.py">
108110
<SubType>Code</SubType>
109111
</Compile>
112+
<Compile Include="scripts_vgg\view_images_vgg.py" />
110113
<Compile Include="script_objdetect\by_segmentation_filtered.py" />
111114
<Compile Include="script_objdetect\by_segmentation.py">
112115
<SubType>Code</SubType>
113116
</Compile>
117+
<Compile Include="script_transforms\average_resize.py" />
114118
<Compile Include="script_transforms\view_gamma_cont.py" />
115119
<Compile Include="script_transforms\view_adapthist.py" />
116120
<Compile Include="script_transforms\view_unsharp_mask.py" />
@@ -220,7 +224,7 @@ dump_digikam.py -a images -t fid_overlay "C:/Users/Graham Monkman/OneDrive/Docum
220224
<Compile Include="lenscorrection\lenscorrection.py" />
221225
<Compile Include="lenscorrection\lenscorrectiondb.py" />
222226
<Compile Include="lenscorrection\__init__.py" />
223-
<Compile Include="scripts_vgg\view_images.py">
227+
<Compile Include="script_transforms\view_transform_fld.py">
224228
<SubType>Code</SubType>
225229
</Compile>
226230
<Compile Include="script_objdetect\config.py" />
@@ -286,6 +290,7 @@ dump_digikam.py -a images -t fid_overlay "C:/Users/Graham Monkman/OneDrive/Docum
286290
<Folder Include="calibration\nextbase512g\" />
287291
<Folder Include="imgpipes\" />
288292
<Folder Include="bin\" />
293+
<Folder Include="learning\" />
289294
<Folder Include="script_augment\bin\" />
290295
<Folder Include="script_imagepipes\" />
291296
<Folder Include="script_augment\" />
@@ -302,6 +307,7 @@ dump_digikam.py -a images -t fid_overlay "C:/Users/Graham Monkman/OneDrive/Docum
302307
<Folder Include="lenscorrection\" />
303308
<Folder Include="scripts_vgg\" />
304309
<Folder Include="test\bin\images\" />
310+
<Folder Include="test\bin\learning_data\" />
305311
<Folder Include="test\bin\movie\" />
306312
<Folder Include="test\imgpipes\" />
307313
<Folder Include="test\lenscorrection\" />
@@ -346,6 +352,7 @@ dump_digikam.py -a images -t fid_overlay "C:/Users/Graham Monkman/OneDrive/Docum
346352
<Content Include="test\bin\images\pca_test1.jpg" />
347353
<Content Include="test\bin\images\vgg_regions.json" />
348354
<Content Include="test\bin\images\vgg_rotations.json" />
355+
<Content Include="test\bin\learning_data\sonar.all-data.csv" />
349356
<Content Include="test\bin\movie\lobster-lowres.mp4" />
350357
<Content Include="test\bin\movie\test-mpeg_512kb.mp4" />
351358
</ItemGroup>

opencvlib/script_augment/make_train_augmentor.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,6 @@
1414
#make_train_augmentor.py -n 10 "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/roi/all/bass", "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/roi/all/bass/subsamples"
1515
import argparse
1616
from os import path
17-
import tempfile
18-
import os
19-
import glob
2017

2118
import random
2219
import shutil
@@ -29,9 +26,6 @@
2926
import funclib.iolib as iolib
3027
from opencvlib.imgpipes.generators import FromPaths
3128
from opencvlib import transforms
32-
from opencvlib.display_utils import KeyBoardInput as Keys
33-
from opencvlib.view import show
34-
3529

3630

3731
def chkempty(dirs):

opencvlib/script_augment/make_train_imgaug.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# pylint: disable=C0103, too-few-public-methods, locally-disabled, no-self-use, unused-argument
1+
#pylint: skip-file
22
'''
33
Generate training images with random corrections
44
and distortions. This is used to generate
@@ -14,7 +14,7 @@
1414
#make_train_imgaug.py -n 10 "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/roi/all/bass", "C:/Users/Graham Monkman/OneDrive/Documents/PHD/images/bass/fiducial/roi/all/bass/subsamples"
1515
import argparse
1616
from os import path
17-
import os
17+
1818

1919
import random
2020
import shutil
@@ -27,8 +27,8 @@
2727
import funclib.iolib as iolib
2828
from opencvlib.imgpipes.generators import FromPaths
2929
from opencvlib import transforms
30-
from opencvlib.display_utils import KeyBoardInput as Keys
31-
from opencvlib.view import show
30+
31+
3232

3333

3434

0 commit comments

Comments
 (0)