Skip to content

Commit

Permalink
Uploading files
Browse files Browse the repository at this point in the history
  • Loading branch information
Tanner Swanson committed Nov 26, 2024
0 parents commit 613b7d8
Show file tree
Hide file tree
Showing 2 changed files with 145 additions and 0 deletions.
77 changes: 77 additions & 0 deletions PopulateTrainingData.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import numpy as np
from perlin_noise import PerlinNoise
import random
import sys
import cv2

def Generate_Perlin_Noise(): # generates 100x100 map of perlin noise
noise = PerlinNoise(octaves=10, seed=int(random.random()))
xpix, ypix = 100, 100
img = np.array([[noise([i / xpix, j / ypix]) for j in range(xpix)] for i in range(ypix)], dtype=np.float32)
return PossibleAnomaly(img) # possibly add anomaly to the result

def ShipHull_Gen(): # creates a 256x256 map of gradient
row_values = np.repeat(np.arange(256), 1)
result_array = np.tile(row_values[:, None], (1, 256))
return PossibleAnomaly(result_array) # possibly add anomaly to the result

def Add_Anomaly(img, xSize, ySize, xPos, yPos, shape):
anomaly_size = (xSize, ySize)
center = (xPos, yPos)

mask = np.zeros_like(img, dtype=np.uint8)

if (shape == 0): # ellipse
cv2.ellipse(mask, center, anomaly_size, angle=0, startAngle=0, endAngle=360, color=255, thickness=-1)
elif (shape == 1): #square
print("Unimpemeneted: square anomaly")
#return
elif (shape == 2): # other?
print("unimplemented: other anomaly")
#return

img[mask == 255] = 1.0 # set all values in mask range to 1.0
return img

def WriteToFile(fileName, fileval):
with open(fileName, "w") as f:
vals = np.array2string(
fileval,
precision=16, # Precision for floating point values
suppress_small=False, # Avoid suppressing small values
separator=', ',
threshold=np.prod(fileval.shape) # Prevent truncation for large arrays
)
f.write(vals)

def PossibleAnomaly(img):
# TODO:
Xsize, Ysize = img.shape[0], img.shape[1]
if random.randint(0, 1) == 1: # if random int = 1, we add anomaly
print("Adding anomaly")
xPos = random.randint(0, Xsize)
yPos = random.randint(0, Ysize)

shape = random.randint(0, 2)

img = Add_Anomaly(img, Xsize, Ysize, xPos, yPos, shape)
return img


if __name__ == "__main__":
filePath = "TrainingData/"

iterations_for_perlin = int(sys.argv[1])
iterations_for_hull = int(sys.argv[2])


for i in range(0, iterations_for_hull):
fileName = filePath + f"hull_gradient{i}"
arr = ShipHull_Gen()

WriteToFile(fileName, arr)

for i in range(0, iterations_for_perlin):
fileName = filePath + f"perlin{i}"
arr = Generate_Perlin_Noise()
WriteToFile(fileName, arr)
68 changes: 68 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import numpy as np
from scipy.ndimage import gaussian_laplace, convolve
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import cv2
import ast
import sys

def get_anomaly_map(img, params):
f_bank = np.zeros((img.shape[0], img.shape[1], params['n_scales'])) # create a filter bank

for i in range(params['n_scales']):
img_sd = scale_down(img, params['scales'][i]) # scale down
img_log = gaussian_laplace(img_sd, sigma=params['log_kernel']) # LoG filtering
img_su = scale_up(img_log, img.shape) # scale up
img_su = (img_su - np.min(img_su)) / (np.max(img_su) - np.min(img_su)) # normalize
f_bank[:, :, i] = img_su # add to filter bank

diff_kernel = np.ones((3, 3, params['n_scales'])) # Histogram difference metric for local
diff_kernel[1, 1, :] = -8 # variation of a pixel w.r.t. its neighbors
sal_map = convolve(f_bank, diff_kernel) # Convultion of filter bank

return sal_map

def scale_down(img, scale): # scale to lower size to reduce computation
new_size = (int(img.shape[0] * scale), int(img.shape[1] * scale))
img_sd = cv2.resize(img, new_size, interpolation=cv2.INTER_AREA)
return img_sd

def scale_up(img, target_shape): # scale back up for the filter bank
img_su = cv2.resize(img, (target_shape[0], target_shape[1]), interpolation=cv2.INTER_LINEAR)
return img_su

if __name__ == "__main__":
if (len(sys.argv) < 3):
print("Error!")
else:
inputData = sys.argv[1]
clippingValue = int(sys.argv[2])
fileName = inputData.split("/")[1] # get the file name, drop the TrainingData/

with open(inputData, "r") as f:
strData = f.read()
npArray = np.array(ast.literal_eval(strData), dtype=np.float32)

params = {
'n_scales': 1,
'scales': [1], # Scale factors
'log_kernel': 1.5 # LoG kernel size
}

anomaly_map = get_anomaly_map(npArray, params)
anomaly_map_clipped = anomaly_map # dont clip
if clippingValue == 2:
anomaly_map_clipped = np.clip(anomaly_map, 0, 1) # limit range from 0 - 1. If outside, round to that value
elif clippingValue == 3:
anomaly_map_clipped = np.where(anomaly_map >= 0.5, 1, 0) # set value to either 0 or 1. rounds up if >= 0.5, else down

plt.imshow(npArray, cmap='hot')
plt.title("Original Map")
plt.colorbar()
plt.savefig(f"OutputData/{fileName}_{clippingValue}_original")

plt.imshow(anomaly_map_clipped, cmap='hot')
plt.title("Anomaly Map")
plt.colorbar()
plt.savefig(f"OutputData/{fileName}_{clippingValue}_analyzed")

0 comments on commit 613b7d8

Please sign in to comment.