Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
huongljn-image-denoising-patterns-1.py
!pip install fastai==1.0.53
!pip install imgaug==0.2.9
!pip install opencv-python==4.1.0
from imgaug import augmenters as iaa
from imgaug import parameters as iap
from fastai.vision import open_image, brightness, image2np
import numpy as np
import random
import cv2
import os
import tqdm
import io
def crapify_directory(inpath, outpath):
outpath.mkdir(exist_ok=True, parents=True)
for f in tqdm.tqdm(inpath.ls()):
if os.path.splitext(f)[1] not in ['.png', '.jpg', '.jpeg']:
continue
img = cv2.imread(str(f))
crap_img = crapify_image(img)
fn = os.path.basename(f)
cv2.imwrite(str(outpath / fn), crap_img)
def crapify_image(img):
height, width, _ = img.shape
for patch in get_patches(height * 2/3, width-1):
if random.random() < 0.85:
add_random_pattern_noise(img, patch, random.choice(PATTERNS_1))
background = random.choice(PATTERNS_2)
row, col = int(background.shape[0] * (random.random() + 0.5)), int(background.shape[1] * (random.random() + 0.5))
background = cv2.resize(background, (col, row))
for i in range(random.randint(20,35)):
m = random.randint(int(height * 2/3), int(height-row-1))
n = random.randint(0, int(width-1-col))
add_random_pattern_noise(img, (m, m+row, n, n+col), background)
img = random_ajust_brightness(img)
return img
PATTERNS_1 = [
cv2.imread(f'patterns/group{g}/pattern{p}.png')
for g in range(1, 5)
for p in range(5)
]
PATTERNS_2 = [
cv2.imread("patterns/pattern_11.png"),
cv2.imread("patterns/pattern_test46.png")
]
def get_patches(height, width, nh=4, nw=6):
""" Splits a retangle of size height x height in nh x nw equal small retangles """
index = 30 if height < 200 else 60
width = width - 1
for k in range(0, nh):
a0 = int(height*k/nh) + index
a1 = int(height*(k+1)/nh) + index
for i in range(0, nw):
b0 = int(width*i/nw)
b1 = int(width*(i+1)/nw)
yield a0, a1, b0, b1
def add_random_pattern_noise(img, patch, pattern_img):
a0, a1, b0, b1 = patch
p = random.randint(-10,100)
pattern_img = cv2.addWeighted(pattern_img, 1, pattern_img, 0, p)
pattern_img = cv2.resize(pattern_img, (int(b1-b0), int(a1-a0)))
img[a0:a1, b0:b1, :] = cv2.min(pattern_img, img[a0:a1, b0:b1, :])
def random_ajust_brightness(img):
height, width, _ = img.shape
if random.random() < 0.7:
if height < 300:
blurer = iaa.Alpha(iap.Choice([0.52, 0.5]),iaa.AverageBlur(2))
else:
blurer = iaa.Alpha(iap.Choice([0.52, 0.5]), iaa.MedianBlur((5, 5)))
return blurer.augment_image(img)
else:
img = cv2_to_fastai(img)
change = random.uniform(0.05,0.2)
brightness(img, change)
img = fastai_to_cv2(img)
return img
def cv2_to_fastai(img):
f = io.BytesIO(cv2.imencode(".jpg", img)[1])
return open_image(f)
def fastai_to_cv2(img):
return image2np(img.data * 255).astype(np.uint8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment