Simon Thomine commited on
Commit
94e4abf
1 Parent(s): 7973387

add cutpaste defect

Browse files
Files changed (3) hide show
  1. app.py +1 -1
  2. source/cutpaste.py +114 -0
  3. source/defectGenerator.py +17 -2
app.py CHANGED
@@ -46,7 +46,7 @@ with gr.Blocks(css="style.css") as demo:
46
  with gr.Group():
47
  with gr.Row():
48
  category_input = gr.Dropdown(label="Select object", choices=list(images.keys()),value="Bottle")
49
- defect_type_input = gr.Dropdown(label="Select type of defect", choices=["blurred", "nsa","structural", "textural" ],value="nsa")
50
  submit = gr.Button(
51
  scale=1,
52
  variant='primary'
 
46
  with gr.Group():
47
  with gr.Row():
48
  category_input = gr.Dropdown(label="Select object", choices=list(images.keys()),value="Bottle")
49
+ defect_type_input = gr.Dropdown(label="Select type of defect", choices=["blurred", "nsa","structural", "textural","cutpaste" ],value="nsa")
50
  submit = gr.Button(
51
  scale=1,
52
  variant='primary'
source/cutpaste.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import numpy as np
3
+ from torchvision import transforms
4
+ from PIL import Image
5
+
6
+ class CutPaste(object):
7
+
8
+ def __init__(self, transform = True, type = 'binary'):
9
+
10
+ '''
11
+ This class creates to different augmentation CutPaste and CutPaste-Scar. Moreover, it returns augmented images
12
+ for binary and 3 way classification
13
+
14
+ :arg
15
+ :transform[binary]: - if True use Color Jitter augmentations for patches
16
+ :type[str]: options ['binary' or '3way'] - classification type
17
+ '''
18
+ self.type = type
19
+ if transform:
20
+ self.transform = transforms.ColorJitter(brightness = 0.1,
21
+ contrast = 0.1,
22
+ saturation = 0.1,
23
+ hue = 0.1)
24
+ else:
25
+ self.transform = None
26
+
27
+ @staticmethod
28
+ def crop_and_paste_patch(image, patch_w, patch_h, transform, rotation=False):
29
+ """
30
+ Crop patch from original image and paste it randomly on the same image.
31
+
32
+ :image: [PIL] _ original image
33
+ :patch_w: [int] _ width of the patch
34
+ :patch_h: [int] _ height of the patch
35
+ :transform: [binary] _ if True use Color Jitter augmentation
36
+ :rotation: [binary[ _ if True randomly rotates image from (-45, 45) range
37
+
38
+ :return: augmented image
39
+ """
40
+
41
+ org_w, org_h = image.size
42
+ mask = None
43
+
44
+ patch_left, patch_top = random.randint(0, org_w - patch_w), random.randint(0, org_h - patch_h)
45
+ patch_right, patch_bottom = patch_left + patch_w, patch_top + patch_h
46
+ patch = image.crop((patch_left, patch_top, patch_right, patch_bottom))
47
+ if transform:
48
+ patch= transform(patch)
49
+
50
+ if rotation:
51
+ random_rotate = random.uniform(*rotation)
52
+ patch = patch.convert("RGBA").rotate(random_rotate, expand=True)
53
+ mask = patch.split()[-1]
54
+
55
+ # new location
56
+ paste_left, paste_top = random.randint(0, org_w - patch_w), random.randint(0, org_h - patch_h)
57
+ aug_image = image.copy()
58
+ aug_image.paste(patch, (paste_left, paste_top), mask=mask)
59
+
60
+ # Create a mask of the pasted area
61
+ paste_right, paste_bottom = paste_left + patch_w, paste_top + patch_h
62
+ paste_mask = Image.new('L', image.size, 0)
63
+ paste_mask.paste(255, (paste_left, paste_top, paste_right, paste_bottom))
64
+
65
+ return aug_image,paste_mask
66
+
67
+ def cutpaste(self, image, area_ratio = (0.02, 0.15), aspect_ratio = ((0.3, 1) , (1, 3.3))):
68
+ '''
69
+ CutPaste augmentation
70
+
71
+ :image: [PIL] - original image
72
+ :area_ratio: [tuple] - range for area ratio for patch
73
+ :aspect_ratio: [tuple] - range for aspect ratio
74
+
75
+ :return: PIL image after CutPaste transformation
76
+ '''
77
+
78
+ img_area = image.size[0] * image.size[1]
79
+ patch_area = random.uniform(*area_ratio) * img_area
80
+ patch_aspect = random.choice([random.uniform(*aspect_ratio[0]), random.uniform(*aspect_ratio[1])])
81
+ patch_w = int(np.sqrt(patch_area*patch_aspect))
82
+ patch_h = int(np.sqrt(patch_area/patch_aspect))
83
+ cutpaste,paste_mask = self.crop_and_paste_patch(image, patch_w, patch_h, self.transform, rotation = False)
84
+ return cutpaste,paste_mask
85
+
86
+ def cutpaste_scar(self, image, width = [2,16], length = [10,25], rotation = (-45, 45)):
87
+ '''
88
+
89
+ :image: [PIL] - original image
90
+ :width: [list] - range for width of patch
91
+ :length: [list] - range for length of patch
92
+ :rotation: [tuple] - range for rotation
93
+
94
+ :return: PIL image after CutPaste-Scare transformation
95
+ '''
96
+ patch_w, patch_h = random.randint(*width), random.randint(*length)
97
+ cutpaste_scar,paste_mask = self.crop_and_paste_patch(image, patch_w, patch_h, self.transform, rotation = rotation)
98
+ return cutpaste_scar,paste_mask
99
+
100
+ def __call__(self, image):
101
+ '''
102
+
103
+ :image: [PIL] - original image
104
+ :return: if type == 'binary' returns original image and randomly chosen transformation, else it returns
105
+ original image, an image after CutPaste transformation and an image after CutPaste-Scar transformation
106
+ '''
107
+ if self.type == 'binary':
108
+ aug = random.choice([self.cutpaste, self.cutpaste_scar])
109
+ return image, aug(image)
110
+
111
+ elif self.type == '3way':
112
+ cutpaste = self.cutpaste(image)
113
+ scar = self.cutpaste_scar(image)
114
+ return image, cutpaste, scar
source/defectGenerator.py CHANGED
@@ -8,6 +8,7 @@ import glob
8
  from source.perlin import rand_perlin_2d_np
9
  import matplotlib.pyplot as plt
10
  from source.nsa import backGroundMask,patch_ex
 
11
 
12
  class TexturalAnomalyGenerator():
13
  def __init__(self, resize_shape=None,dtd_path="../../datasets/dtd/images"):
@@ -99,6 +100,7 @@ class DefectGenerator():
99
 
100
  self.texturalAnomalyGenerator=TexturalAnomalyGenerator(resize_shape,dtd_path)
101
  self.structuralAnomalyGenerator=StructuralAnomalyGenerator(resize_shape)
 
102
 
103
  self.resize_shape=resize_shape
104
  self.rot = iaa.Sequential([iaa.Affine(rotate=(-90, 90))])
@@ -165,11 +167,21 @@ class DefectGenerator():
165
  msk = transform(msk)*255.0
166
  return image,msk
167
 
 
 
 
 
 
 
 
 
 
 
168
 
169
 
170
  def genSingleDefect(self,image,label,mskbg):
171
- if label.lower() not in ["textural","structural","blurred","nsa"]:
172
- raise ValueError("The defect type should be in ['textural','structural','blurred','nsa']")
173
 
174
  if (label.lower()=="textural" or label.lower()=="structural" or label.lower()=="blurred"):
175
  imageT=self.toTensor(image)
@@ -182,6 +194,9 @@ class DefectGenerator():
182
  return self.generateBlurredDefectiveImage(imageT,bmask)
183
  elif (label.lower()=="nsa"):
184
  return self.generateNsaDefect(image,mskbg)
 
 
 
185
 
186
  def genDefect(self,image,defectType,category="",return_list=False):
187
  mskbg=backGroundMask(image,obj=category)
 
8
  from source.perlin import rand_perlin_2d_np
9
  import matplotlib.pyplot as plt
10
  from source.nsa import backGroundMask,patch_ex
11
+ from source.cutpaste import CutPaste
12
 
13
  class TexturalAnomalyGenerator():
14
  def __init__(self, resize_shape=None,dtd_path="../../datasets/dtd/images"):
 
100
 
101
  self.texturalAnomalyGenerator=TexturalAnomalyGenerator(resize_shape,dtd_path)
102
  self.structuralAnomalyGenerator=StructuralAnomalyGenerator(resize_shape)
103
+ self.cutpaste=CutPaste()
104
 
105
  self.resize_shape=resize_shape
106
  self.rot = iaa.Sequential([iaa.Affine(rotate=(-90, 90))])
 
167
  msk = transform(msk)*255.0
168
  return image,msk
169
 
170
+ def generateCutPasteDefect(self, image,bMask):
171
+ msk=np.zeros((self.resize_shape[0], self.resize_shape[1]))
172
+ while (np.count_nonzero(msk)<100):
173
+ defect,cpmsk=self.cutpaste.cutpaste(image)
174
+ msk=bMask*np.expand_dims(np.array(cpmsk),axis=2)
175
+ image=np.array(defect)*bMask + np.array(image)*(1-bMask)
176
+ transform=T.ToTensor()
177
+ image = transform(image)
178
+ msk = transform(msk)
179
+ return image,msk
180
 
181
 
182
  def genSingleDefect(self,image,label,mskbg):
183
+ if label.lower() not in ["textural","structural","blurred","nsa","cutpaste"]:
184
+ raise ValueError("The defect type should be in ['textural','structural','blurred','nsa','cutpaste']")
185
 
186
  if (label.lower()=="textural" or label.lower()=="structural" or label.lower()=="blurred"):
187
  imageT=self.toTensor(image)
 
194
  return self.generateBlurredDefectiveImage(imageT,bmask)
195
  elif (label.lower()=="nsa"):
196
  return self.generateNsaDefect(image,mskbg)
197
+ elif (label.lower()=="cutpaste"):
198
+ return self.generateCutPasteDefect(image,mskbg)
199
+
200
 
201
  def genDefect(self,image,defectType,category="",return_list=False):
202
  mskbg=backGroundMask(image,obj=category)