def apply_sobel_edge_y(mask_size): mask,sum,m2,n2= create_mask(mask_size) d=len(mask) for x in range(-m2,m2+1): for y in range(-n2,n2+1): if not((x*x + y*y)==0): mask[x + m2][y + n2] = round(y / (x*x + y*y),3) return mask,sum,m2,n2
def load_images_to_memory(file_names, shape=sc.size): batch_shape = (len(file_names),) + shape + (3,) mask_batch_shape = (len(file_names),) + (shape[0]-mask.win_size[0]+1, shape[1]-mask.win_size[1]+1) data = np.empty(batch_shape, dtype=np.uint8) masks = np.empty(mask_batch_shape, dtype=bool) for idx, file_name in enumerate(file_names): img = scipy.misc.imread(file_name) img = scipy.misc.imresize(img, shape) data[idx] = img masks[idx] = mask.create_mask(basename(file_name.replace('\\', '/'))) print("Loaded %i/%i: %s" % (idx+1, len(file_names), file_name), end='\r') return data, masks
def create_gaussian(mask_size,sigma): mask,sum,m2,n2= create_mask(mask_size) # Loops Through Mask To Set Each Value Of The Mask for x in range(-m2,m2+1): for y in range(x,n2+1): # Formula Provided From Slides mask[x + m2][y + n2] = round(float(float(1) / (2 * math.pi * sigma * sigma)) * float(math.exp(-((x * x) + (y * y)) / (2.0 * sigma * sigma))), 3) if(x != y): mask[y + n2][x + m2] = mask[x + m2][y + n2] sum += 2 * mask[x + m2][y + n2] else: sum += mask[x + m2][y + n2] return mask,sum,m2,n2
def create_unweighted(mask_size): mask,sum,m2,n2= create_mask(mask_size) d=len(mask) for x in range(-m2,m2+1): for y in range(x,n2+1): mask[x + m2][y + n2] = round(1/((d*d)),3) if(x != y): mask[y + n2][x + m2] = mask[x + m2][y + n2] sum += 2 * mask[x + m2][y + n2] else: sum += mask[x + m2][y + n2] return mask,sum,m2,n2
def create_weighted(mask_size): mask,sum,m2,n2= create_mask(mask_size) d=len(mask) # Loops Through Mask To Set Each Value Of The Mask for x in range(-m2,m2+1): for y in range(x,n2+1): # Checks If Its The Center Index Of The Mask # Else It Sets It To Default Formula if (x==math.floor((-m2+(m2+1))/2)) and (y==math.floor((-m2+(m2+1))/2)): mask[x + m2][y + n2] = round(2/((d*d)+1),3) else: mask[x + m2][y + n2] = round(1/((d*d)+1),3) if(x != y): mask[y + n2][x + m2] = mask[x + m2][y + n2] sum += 2 * mask[x + m2][y + n2] else: sum += mask[x + m2][y + n2] return mask,sum,m2,n2
def apply_median_filter(mask_size,img): M,N= img.shape g=img.copy() mask_,sum,m2,n2=mask.create_mask(mask_size) mean=[] # Loops Through Each Pixel In The Image Being Changed for i in range(m2,M-m2): for j in range(n2,N-n2): sum=0.0 #Loops Through Mask And Checks For The Median Value for x in range(-m2,m2+1): for y in range(-n2,n2+1): #Sets Each Value Of Image To The mask_ mask_[x+m2][y+n2]=img[i+x][j+y] sum=get_mean(mask_) # Turns The Mean Value Into A np.uint8 g[i][j]=np.uint8(sum) return g
import cv2 import os from mask import create_mask FACE_LOC = "./face" # face 폴더에 들어있는 마스크 착용하지 않은 이미지를 조회하며 마스크를 생성한다. images = [os.path.join(FACE_LOC, f) for f in os.listdir(FACE_LOC) if os.path.isfile(os.path.join(FACE_LOC, f))] for i in range(len(images)): print("the path of the image is", images[i]) create_mask(images[i], i) # create_wrong_mask(images[i])
import os import cv2 from mask import create_mask # path of original face images(without_mask) face_folder_path = os.path.join( os.getcwd(), "Data Generator/data/without_mask") face_images = [os.path.join(face_folder_path, f) for f in os.listdir( face_folder_path) if os.path.isfile(os.path.join(face_folder_path, f))] # paath of mask images mask_folder_path = os.path.join(os.getcwd(), "Data Generator/images") mask_images = [os.path.join(mask_folder_path, f) for f in os.listdir( mask_folder_path)if os.path.isfile(os.path.join(mask_folder_path, f))] for i in range(len(face_images)): print("path of original: ", face_images[i]) for j in range(len(mask_images)): create_mask(face_images[i], mask_images[j])
import cv2 import os from mask import create_mask folder_path = "./data/without_mask" # c = 0 images = [ os.path.join(folder_path, f) for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f)) ] for i in range(len(images)): print("the path of the image is", images[i]) # image = cv2.imread(images[i]) # c = c + 1 create_mask(images[i])
variety_mask_path = "./images/" image_path = "./trial/mask/" folder = [ os.path.join(folder_path, f) for f in os.listdir(folder_path) if os.path.isdir(os.path.join(folder_path, f)) ] variety = [ os.path.join(variety_mask_path, f) for f in os.listdir(variety_mask_path) if os.path.isfile(os.path.join(variety_mask_path, f)) ] print('{} and {}'.format(folder, variety)) for k in range(len(folder)): print( '#####################################################################################' ) image_path = folder[k] images = [ os.path.join(image_path, f) for f in os.listdir(image_path) if os.path.isfile(os.path.join(image_path, f)) ] for j in range(len(variety)): for i in range(len(images)): print( f'Editing {os.path.split(folder[k])[1]} with {os.path.split(variety[j])[1]} at {images[i]}' ) # print('image path: {} and mask variety path: {} '.format(images[i], variety[j])) create_mask(images[i], variety[j])
blue_path = os.path.join(os.getcwd(),"create_mask/blue.png") # black_path = os.path.join(os.getcwd(),"create_mask/black.png") mask_list.append(default_path) mask_list.append(white_path) mask_list.append(blue_path) # mask_list.append(black_path) print(mask_list) dataset_path = 'dataset' if not os.path.exists('dataset_with_mask'): os.mkdir('dataset_with_mask') for i in os.listdir('dataset'): if not os.path.exists(f'dataset_with_mask/{i}'): os.mkdir(f'dataset_with_mask/{i}') imagePaths = [] for i in os.listdir('dataset'): for j in os.listdir(f'dataset/{i}'): imagePaths.append(f'dataset/{i}/{j}') for i in tqdm(imagePaths,total=len(imagePaths)): mask_path = random.choice(mask_list) create_mask(i,mask_path)
def expanding_block(filename, *, debug=False): """ Tests an image for copy-move forgery (a portion of an image has been copied and then moved somewhere else within the image.) Written by Efron Licht, based off the algorithm "An efficient expanding block algorithm for image copy-move forgery detection" by Gavin Lynch, Frank Y. Shih, and Hong-Yuan Mark Liao, and published in Information Sciences 239 in 2013. Free for noncommerical use or modification, but please retain the above credits. Please ask for commerical use. input: filename that contains an mxn image (color or grayscale) known valid formats: '.png', '.jpg' output: imageConsideredModified, imgOut where imageConsideredModified is True | False if imageConsideredModified == True, imgOut is the original image if imageConsideredModified == False, imgOut is a (2m+8) x n x 3 image """ """ file IO and conversion to grayscale: """ baseImg = io.imread(filename) try: # color.rgb2gray converts to doubles on unit scale (0<pixel<1) # so we rescale back to uint8 img = np.uint8(255 * color.rgb2gray(baseImg)) except ValueError as valError: shape = np.shape(baseImg) if shape[2] == 1: # image is grayscale already img = baseImg # convert image into a a 3D array (psuedo-RGB) so as to not handle # so many unique cases later baseImg = np.uint8(255 * color.gray2rgb(baseImg)) else: raise valError init = ExpandingBlockInit(img) rows = np.shape(img)[0] - init.blockSize cols = np.shape(img)[1] - init.blockSize blocks = ([ Block(img, row, col, init) for row in range(rows) for col in range(cols) ]) blocks = sorted(blocks, key=lambda block: block.variance) """ remove elements with too low of variance to cut down on false positives due to bad white balance on source camera or areas of block color """ blocks = [block for block in blocks if not block.tooLowVariance] """ assign blocks as evenly as possible to groups """ groups = [[] for x in range(init.numBuckets)] # we don't want to use * to avoid nasty by-reference bugs blocksPerBucket = len(blocks) / init.numBuckets group = 0 count = 0 for block in blocks: groups[group].append(block) count += 1 if count > blocksPerBucket: group += 1 count -= blocksPerBucket """ assign groups to buckets """ buckets = [None] * init.numBuckets for n in range(init.numBuckets): try: buckets[n] = groups[n - 1] + groups[n] + groups[n + 1] except IndexError: if n == init.numBuckets - 1: buckets[n] = groups[n - 1] + groups[n] else: raise IndexError """ process buckets for pixel-to-pixel similiarity. see process_bucket """ buckets = [process_bucket(bucket) for bucket in buckets] """ recombine buckets after processing, removing empty buckets """ blocks = [block for bucket in buckets for block in bucket] """ if there are no blocks left, the image is clean """ if len(blocks) == 0: imageConsideredModified = False return imageConsideredModified, baseImg #else imageConsideredModified = True """ otherwise, we create a masked image to show where the modification occurs """ mask = create_mask(blocks, baseImg, init) imgOut = np.uint8(write_mask(mask, baseImg)) if debug: io.imshow(imgOut) return imageConsideredModified, imgOut
def expanding_block(filename, *, _debug=False): """ Tests an image for copy-move forgery (a portion of an image has been copied and then moved somewhere else within the image.) Written by Efron Licht, based off the algorithm "An efficient expanding block algorithm for image copy-move forgery detection" by Gavin Lynch, Frank Y. Shih, and Hong-Yuan Mark Liao, and published in Information Sciences 239 in 2013. Free for noncommerical use or modification, but please retain the above credits. Please ask for commerical use. input: filename that contains an mxn image (color or grayscale) known valid formats: '.png', '.jpg' output: imageConsideredModified, imgOut where imageConsideredModified is True | False if imageConsideredModified == True, imgOut is the original image if imageConsideredModified == False, imgOut is a (2m+8) x n x 3 image """ """ helper functions """ def _generate_groups(blocks): """ assign blocks within image evenly to groups""" group = [] blocksPerGroup = len(blocks) / init.numBuckets group = 0 count = 0 for block in blocks: if len(group) >= blocksPerGroup: yield group count -= blocksPerGroup group = [] group.append(block) count += 1 if len(group) > 0: yield group def _generate_buckets(groups): """ assign blocks within groups to overlapping buckets """ for n in range(len(groups)): try: bucket = groups[n - 1] + groups[n] + groups[n + 1] except IndexError: if n == init.numBuckets - 1: bucket = groups[n - 1] + groups[n] else: raise yield bucket """ MAIN FUNCTION START """ #0. file IO and conversion to grayscale: baseImg = io.imread(filename) try: # color.rgb2gray converts to doubles on unit scale (0<pixel<1) # so we rescale back to uint8 img = np.uint8(255 * color.rgb2gray(baseImg)) except ValueError: shape = np.shape(baseImg) if shape[2] == 1: # image is grayscale already img = baseImg # convert image into a a 3D array (psuedo-RGB) so as to not handle # so many unique cases later baseImg = np.uint8(255 * color.gray2rgb(baseImg)) else: raise init = ExpandingBlockInit(img) rows, cols, *_ = np.shape(img) - init.blockSize blocks = ((Block(img, row, col, init) for row in range(rows) for col in range(cols))) blocks = sorted(blocks, key=lambda block: block.variance) #1. remove elements with too low of variance to cut down on false positives # due to bad white balance on source camera or areas of block color blocks = dropwhile(lambda block: block.tooLowVariance, blocks) #2. assign blocks as evenly as possible to groups groups = _generate_groups(blocks) #3. assign blocks in neighboring groups to overlapping buckets buckets = _generate_buckets(groups) #4. process buckets for pixel-to-pixel similiarity. see process_bucket buckets = (process_bucket(bucket) for bucket in buckets) #buckets now hold blocks that we think are modified. #5. recombine buckets after processing blocks = [block for bucket in buckets for block in bucket] #6a. Image is considered clean if no blocks left after processing if len(blocks) == 0: imageConsideredModified = False imgOut = baseImg #6b. If image is considered modified,create mask for image else: imageConsideredModified = True mask = create_mask(blocks, baseImg, init) #7b. Paint mask over image imgOut = np.uint8(write_mask(mask, baseImg)) #8. Output. if _debug: io.imshow(imgOut) return imageConsideredModified, imgOut
def mask_dataframe(df, n_samples=0, dataset_splits=None, random_masks=False): counts = {'success': 0, 'failed': 0} if dataset_splits is None: print( "Error. Please provide appropriate data splits / genders for the mask data" ) return elif sum([d for d in dataset_splits.values()]) != 1: print("Error. Please ensure data splits add up to 1") return # create trackers for each gender of size t_size t_size = 10 gender_tracker = [[k] * math.floor(v * t_size) for k, v in dataset_splits.items()] gender_tracker = [y for x in gender_tracker for y in x] random.shuffle(gender_tracker) current_num = {} for g in genders.values(): current_num[g] = 0 # iterate through labels for label, item in df.iterrows(): # limit number of items processed if sum([c for c in counts.values()]) == n_samples: break # sort file and create new savepath gender = genders.get(item['gender']) if gender is None: print('No gender assigned. Skipping.') counts['failed'] += 1 continue dataset_name = gender_tracker[current_num[gender]] new_save_path = os.path.join(current_dir, results_path, dataset_name, gender) # get filename header = 'coarse_tilt_aligned_face' face_id = item['face_id'] image = item['original_image'] filename = '.'.join([header, str(face_id), image]) # get file path face = os.path.join(faces_path, item['user_id'], filename) # validate file path if os.path.exists(face): print(f'Loading face from {face}') else: print(f'File {face} does not exist') continue # create mask - return True if success, False if failed if create_mask(image_path=face, save_path=new_save_path, random_masks=random_masks): # increment current num for gender if success current_num[gender] += 1 if current_num[gender] >= t_size: current_num[gender] = 0 counts['success'] += 1 else: counts['failed'] += 1 print(counts)
except: print('Open Error!') else: r_image, boxes = yolo.detect_image(image) r_image.show() return boxes boxes = get_boxes(filepath) box_index = input('Input the indexes you want to remove:') box_index = box_index.split(',') print(box_index) # Create the mask image for the objects selected. mask = M.create_mask(filepath) for index in box_index: index = int(index) mask = M.add_mask(mask, boxes[index][0], boxes[index][1], boxes[index][2], boxes[index][3]) mask_name = 'mask/' + filename.split('.')[0] + '_mask.jpg' M.save_mask(mask, mask_name) elif choose == str(2): filename = input('Input the image name:') filepath = 'image/' + filename ps = get_patchsize(filepath) m_name = input('Input the mask name:') mask_name = 'mask/' + m_name else:
def expanding_block(filename, *, _debug = False): """ Tests an image for copy-move forgery (a portion of an image has been copied and then moved somewhere else within the image.) Written by Efron Licht, based off the algorithm "An efficient expanding block algorithm for image copy-move forgery detection" by Gavin Lynch, Frank Y. Shih, and Hong-Yuan Mark Liao, and published in Information Sciences 239 in 2013. Free for noncommerical use or modification, but please retain the above credits. Please ask for commerical use. input: filename that contains an mxn image (color or grayscale) known valid formats: '.png', '.jpg' output: imageConsideredModified, imgOut where imageConsideredModified is True | False if imageConsideredModified == True, imgOut is the original image if imageConsideredModified == False, imgOut is a (2m+8) x n x 3 image """ """ helper functions """ def _generate_groups(blocks): """ assign blocks within image evenly to groups""" group = [] blocksPerGroup = len(blocks) / init.numBuckets group = 0 count = 0 for block in blocks: if len(group) >= blocksPerGroup: yield group count -= blocksPerGroup group = [] group.append(block) count += 1 if len(group) > 0: yield group def _generate_buckets(groups): """ assign blocks within groups to overlapping buckets """ for n in range(len(groups)): try: bucket = groups[n-1] + groups[n] + groups[n+1] except IndexError: if n == init.numBuckets-1: bucket = groups[n-1]+groups[n] else: raise yield bucket """ MAIN FUNCTION START """ #0. file IO and conversion to grayscale: baseImg = io.imread(filename) try: # color.rgb2gray converts to doubles on unit scale (0<pixel<1) # so we rescale back to uint8 img = np.uint8(255*color.rgb2gray(baseImg)) except ValueError: shape = np.shape(baseImg) if shape[2] == 1: # image is grayscale already img = baseImg # convert image into a a 3D array (psuedo-RGB) so as to not handle # so many unique cases later baseImg = np.uint8(255*color.gray2rgb(baseImg)) else: raise init = ExpandingBlockInit(img) rows, cols, *_ = np.shape(img)-init.blockSize blocks = ((Block(img, row, col, init) for row in range(rows) for col in range(cols)) ) blocks = sorted(blocks, key = lambda block: block.variance) #1. remove elements with too low of variance to cut down on false positives # due to bad white balance on source camera or areas of block color blocks = dropwhile(lambda block: block.tooLowVariance, blocks) #2. assign blocks as evenly as possible to groups groups = _generate_groups(blocks) #3. assign blocks in neighboring groups to overlapping buckets buckets = _generate_buckets(groups) #4. process buckets for pixel-to-pixel similiarity. see process_bucket buckets = (process_bucket(bucket) for bucket in buckets) #buckets now hold blocks that we think are modified. #5. recombine buckets after processing blocks = [block for bucket in buckets for block in bucket] #6a. Image is considered clean if no blocks left after processing if len(blocks) == 0: imageConsideredModified = False imgOut = baseImg #6b. If image is considered modified,create mask for image else: imageConsideredModified = True mask = create_mask(blocks, baseImg, init) #7b. Paint mask over image imgOut = np.uint8(write_mask(mask, baseImg)) #8. Output. if _debug: io.imshow(imgOut) return imageConsideredModified, imgOut