def perform(original_image_path, changed_image_path): original_image = Image.open(original_image_path) changed_image = Image.open(changed_image_path) w, h = original_image.size tile_size = 64 hash_length = 64 threshold = hash_length * 0.15 column, row = count_tiles_size(w, h, tile_size) # Slice image to 64x64 blocks original_tiles = image_slicer.slice(original_image_path, number_tiles=column * row, col=column, row=row, save=False) changed_tiles = image_slicer.slice(changed_image_path, number_tiles=column * row, col=column, row=row, save=False) # Итеративно проходим по каждому блоку изображения for original_tile, changed_tile in zip(original_tiles, changed_tiles): # Получаем хеш блока original_hash = imagehash.phash_simple(original_tile.image) changed_hash = imagehash.phash_simple(changed_tile.image) # Прям хеш методом наименее значащего бита original_tile.image = lsb.hide(original_tile.image, str(original_hash)) changed_tile.image = lsb.hide(changed_tile.image, str(changed_hash)) # Забираем хеш из изображения decoded_original_hash = lsb.reveal(original_tile.image.copy()) decoded_changed_hash = lsb.reveal(changed_tile.image.copy()) # Вычисляем расстояние Хемминга и сравниваем его с пороговой границей if hamming_distance(decoded_original_hash, decoded_changed_hash) > threshold: # Закрашиваем измененные области # The current version supports all possible conversions between “L”, “RGB” and “CMYK.” The matrix argument only supports “L” and “RGB”. rgb2xyz = (0.412453, 0.357580, 0.180423, 0, 0.212671, 0.215160, 0.072169, 0, 0.019334, 0.919193, 0.950227, 0) changed_tile.image = changed_tile.image.convert("RGB", rgb2xyz) result_image = image_slicer.join(changed_tiles, w, h) file_name = original_image_path.split(".")[-2] result_image_path = original_image_path.replace(file_name, file_name + "_result") result_image.save(result_image_path) original_image.show() changed_image.show() result_image.show()
def hash_picture(self, curr_picture: picture_class.Picture): try: if self.conf.ALGO == configuration.ALGO_TYPE.A_HASH: # Average target_hash = imagehash.average_hash( Image.open(curr_picture.path)) elif self.conf.ALGO == configuration.ALGO_TYPE.P_HASH: # Perception target_hash = imagehash.phash(Image.open(curr_picture.path)) elif self.conf.ALGO == configuration.ALGO_TYPE.P_HASH_SIMPLE: # Perception - simple target_hash = imagehash.phash_simple( Image.open(curr_picture.path)) elif self.conf.ALGO == configuration.ALGO_TYPE.D_HASH: # D target_hash = imagehash.dhash(Image.open(curr_picture.path)) elif self.conf.ALGO == configuration.ALGO_TYPE.D_HASH_VERTICAL: # D-vertical target_hash = imagehash.dhash_vertical( Image.open(curr_picture.path)) elif self.conf.ALGO == configuration.ALGO_TYPE.W_HASH: # Wavelet target_hash = imagehash.whash(Image.open(curr_picture.path)) else: raise Exception('IMAGEHASH WRAPPER : HASH_CHOICE NOT CORRECT') # TO NORMALIZE : https://fullstackml.com/wavelet-image-hash-in-python-3504fdd282b5 curr_picture.hash = target_hash except Exception as e: self.logger.error("Error during hashing : " + str(e)) return curr_picture
def hash_func(self, x): ''''Hash one image and return hash''' x = self.process_for_hash(x) if self.hash_name == "AverageHash": hash_value = imagehash.average_hash(x, hash_size=8, mean=np.mean) elif self.hash_name == "Phash": hash_value = imagehash.phash(x, hash_size=8, highfreq_factor=4) elif self.hash_name == "PhashSimple": hash_value = imagehash.phash_simple(x, hash_size=8, highfreq_factor=4) elif self.hash_name == "DhashH": hash_value = imagehash.dhash(x) elif self.hash_name == "DhashV": hash_value = imagehash.dhash_vertical(x) elif self.hash_name == "Whash": hash_value = imagehash.whash(x, hash_size=8, image_scale=None, mode='haar', remove_max_haar_ll=True) elif self.hash_name == "ColorHash": hash_value = imagehash.colorhash(x, binbits=3) elif self.hash_name == "CropResistantHash": # does not work yet hash_value = imagehash.crop_resistant_hash(x, hash_func=None, limit_segments=None, segment_threshold=128, min_segment_size=500, segmentation_image_size=300 ) else: raise NotImplementedError(f"Hash Name -- {self.hash_name} -- Unknown") return str(hash_value)
def db_add_image(file_name: str) -> bool: image = Image.open(file_name) return db_add(file_name, str(imagehash.average_hash(image)), str(imagehash.phash(image)), str(imagehash.phash_simple(image)), str(imagehash.dhash(image)), str(imagehash.dhash_vertical(image)), str(imagehash.whash(image)), str(imagehash.colorhash(image)))
def Hashing(filename): phash = int(str(imagehash.phash(Image.open(filename))),16) ahash = int(str(imagehash.average_hash(Image.open(filename))),16) phashimple = int(str(imagehash.phash_simple(Image.open(filename))),16) dhash = int(str(imagehash.dhash(Image.open(filename))),16) dhashv = int(str(imagehash.dhash_vertical(Image.open(filename))),16) wash = int(str(imagehash.whash(Image.open(filename))),16) return phash,ahash,phashimple,dhash,dhashv,wash
def getHash(img): normal = Image.open(img).convert('L') crop=normal.crop((25,37,195,150)) ahash = str(imagehash.average_hash(crop)) phash = str(imagehash.phash(crop)) psimplehash = str(imagehash.phash_simple(crop)) dhash = str(imagehash.dhash(crop)) vertdhash = str(imagehash.dhash_vertical(crop)) whash = str(imagehash.whash(crop)) return ahash,phash,psimplehash,dhash,vertdhash,whash
def getHash(img): normal = Image.open(img).convert('L') crop = normal.crop((25, 37, 195, 150)) ahash = str(imagehash.average_hash(crop)) phash = str(imagehash.phash(crop)) psimplehash = str(imagehash.phash_simple(crop)) dhash = str(imagehash.dhash(crop)) vertdhash = str(imagehash.dhash_vertical(crop)) whash = str(imagehash.whash(crop)) return ahash, phash, psimplehash, dhash, vertdhash, whash
def feat_extr(test_set, Nr,Nc, feat_type='phash', eigen=5, hash_size=64, nclass=16): """ Feature extractor from batches of training data """ import imagehash import numpy as np import sklearn.decomposition as deco import binascii as ba import PIL.Image as Image # Supported feature extraction methods methods= ['phash','ahash','tsvd'] # Initialize feature set samples= np.shape(test_set)[0] if feat_type=='phash' or feat_type=='ahash': feat_set= np.zeros( ( samples,int((hash_size**2)/4) ), dtype=np.uint8) elif feat_type=='tsvd': # Define dimension of TSVD feature set and reserve space Nb= samples/nclass maxrank= np.min(Nr*Nc,Nb) feat_set= np.zeros((nclass,maxrank*eigen), dtype=np.uint8) else: # Do nothing; ensemble learning option feat_set= test_set # Loop on classes if feat_type in methods: for ik in range(samples): # Phash case - convert in feature space if feat_type=='phash': feat_set[ik,:]= np.fromstring( ba.hexlify( bytearray.fromhex( imagehash.phash_simple( Image.frombytes('L',(Nr,Nc),np.reshape(test_set[ik,:],(Nr,Nc)) ), hash_size=hash_size ))), dtype=np.uint8) elif feat_type=='ahash': feat_set[ik,:]= np.fromstring( ba.hexlify( bytearray.fromhex( imagehash.average_hash( Image.frombytes('L',(Nr,Nc),np.reshape(test_set[ik,:],(Nr,Nc)) ), hash_size=hash_size ))), dtype=np.uint8) # T-SVD case elif feat_type=='tsvd': # Create decomposition function svd= deco.TruncatedSVD(n_components=eigen, n_iter=7, random_state=42) # Create feature set for ik in range(nclass): feat_set[ik,:]= np.reshape(svd.transform( test_set[ik:(ik+1)*Nb,:] ),(1,maxrank*eigen),order='F') return feat_set
def getHash(img): size = 223, 310 normal = Image.open(img).convert('L') normal = normal.resize(size, Image.ANTIALIAS) crop = normal.crop((25, 37, 195, 150)) ahash = str(imagehash.average_hash(crop)) phash = str(imagehash.phash(crop)) psimplehash = str(imagehash.phash_simple(crop)) dhash = str(imagehash.dhash(crop)) vertdhash = str(imagehash.dhash_vertical(crop)) whash = str(imagehash.whash(crop)) return ahash, phash, psimplehash, phash, vertdhash, whash
def getHash(img): size = 223,310 normal = Image.open(img).convert('L') normal = normal.resize(size, Image.ANTIALIAS) crop=normal.crop((25,37,195,150)) ahash = str(imagehash.average_hash(crop)) phash = str(imagehash.phash(crop)) psimplehash = str(imagehash.phash_simple(crop)) dhash = str(imagehash.dhash(crop)) vertdhash = str(imagehash.dhash_vertical(crop)) whash = str(imagehash.whash(crop)) return ahash,phash,psimplehash,phash,vertdhash,whash
def image_hash(image_file="../gif/test/img/0.png", hash_size=8): im = Image.open(image_file) a_hash_value = imagehash.average_hash(im, hash_size) d_hash_value = imagehash.dhash(im, hash_size) d_hash_value_h = imagehash.dhash_vertical(im, hash_size) p_hash_value = imagehash.phash(im, hash_size) p_hash_value_s = imagehash.phash_simple(im, hash_size) w_hash_value = imagehash.whash(im, hash_size) return [ a_hash_value, d_hash_value, d_hash_value_h, p_hash_value, p_hash_value_s, w_hash_value ]
def hash_picture(self, curr_picture): """ Hash a picture and returns the hash value :param curr_picture: the picture to hash :return: the hashed version of the picture """ answer = {} self.logger.info("Hashing picture ... ") # Convert bytes in PIL image pil_picture = Image.open(io.BytesIO(curr_picture)) self.logger.debug( f"Picture converted to PIL Image {type(pil_picture)}") # DEBUG # pil_picture.save('/home/user/Desktop/debug_pil.bmp') try: # Note : @image must be a PIL instance. if self.fe_conf.A_HASH.get("is_enabled", False): self.logger.debug("A-HASH ... ") answer["A_HASH"] = self.check_null_hash( imagehash.average_hash(pil_picture)) if self.fe_conf.P_HASH.get("is_enabled", False): self.logger.debug("P_HASH ... ") answer["P_HASH"] = self.check_null_hash( imagehash.phash(pil_picture)) if self.fe_conf.P_HASH_SIMPLE.get("is_enabled", False): self.logger.debug("P_HASH_SIMPLE ... ") answer["P_HASH_SIMPLE"] = self.check_null_hash( imagehash.phash_simple(pil_picture)) if self.fe_conf.D_HASH.get("is_enabled", False): self.logger.debug("D_HASH ... ") answer["D_HASH"] = self.check_null_hash( imagehash.dhash(pil_picture)) if self.fe_conf.D_HASH_VERTICAL.get("is_enabled", False): self.logger.debug("D_HASH_VERTICAL ... ") answer["D_HASH_VERTICAL"] = self.check_null_hash( imagehash.dhash_vertical(pil_picture)) if self.fe_conf.W_HASH.get("is_enabled", False): self.logger.debug("W_HASH ... ") answer["W_HASH"] = self.check_null_hash( imagehash.whash(pil_picture)) if self.fe_conf.TLSH.get("is_enabled", False): self.logger.debug("TLSH ... ") answer["TLSH"] = self.check_null_hash(tlsh.hash(curr_picture)) except Exception as e: self.logger.error("Error during hashing : " + str(e)) return answer
def calculateHash(hashAlgorithmString, imageHashDict, imagePath, image, hashSizeInt): if hashAlgorithmString == 'dhash': imageHashDict[imagePath] = dhash(image, hash_size=hashSizeInt) elif hashAlgorithmString == 'dhash_vertical': imageHashDict[imagePath] = dhash_vertical(image, hash_size=hashSizeInt) elif hashAlgorithmString == 'ahash': imageHashDict[imagePath] = average_hash(image, hash_size=hashSizeInt) elif hashAlgorithmString == 'phash': imageHashDict[imagePath] = phash(image, hash_size=hashSizeInt) elif hashAlgorithmString == 'phash_simple': imageHashDict[imagePath] = phash_simple(image, hash_size=hashSizeInt) elif hashAlgorithmString == 'whash_haar': imageHashDict[imagePath] = whash(image, hash_size=hashSizeInt) elif hashAlgorithmString == 'whash_db4': imageHashDict[imagePath] = whash(image, hash_size=hashSizeInt, mode='db4') elif hashAlgorithmString == None: imageHashDict[imagePath] = phash(image, hash_size=hashSizeInt) return imageHashDict
def hash_icons(extractor, folder_icons, mainonly=False, save=True): lookup = [] groups = extractor.get_group_icons() if groups is None: return lookup else: if not os.path.exists(os.path.join(folder_icons)): os.makedirs(os.path.join(folder_icons)) for group in groups: for i, res in enumerate(group): img = extractor.export(group, i) if img: img_avg_hash = imagehash.average_hash(img) img_dhash = imagehash.dhash(img) img_phash = imagehash.phash_simple(img) if save: img.save( os.path.join(folder_icons, str(img_avg_hash) + ".ico")) lookup.append({ 'index': res.ID, 'average_hash': str(img_avg_hash), 'difference_hash': str(img_dhash), 'perception_phash': str(img_phash) }) if mainonly: break if mainonly: break return lookup
def simple_hash(img): normal = Image.open(img).convert('L') hash = str(imagehash.phash_simple(normal)) return int(format(int(hash,16),'064b'))
parser.add_argument("input_file") args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() # imageset = set() goodhash = {} simplehash = {} with open(args.input_file) as filelist: k = 0 print "Starting hashing of images" for line in filelist: impath = os.path.join(args.input_folder, line).strip() I = Image.open(impath) goodhash[str(imagehash.phash(I))] = impath simplehash[str(imagehash.phash_simple(I))] = impath if (k % 2000) == 0: print "Parsed item %d - good %d/%d" % (k, len(goodhash), len(simplehash)) k += 1 print "There are %d/%d unique files in the %d input images" % ( len(goodhash), len(simplehash), k) with open("hash.txt", "wt") as hf: for k in goodhash.keys(): hf.write(goodhash[k] + "\n") with open("simple_hash.txt", "wt") as hf: for k in simplehash.keys(): hf.write(simplehash[k] + "\n")
def getImageHash(image): return { "phash ": imagehash.phash(image), "phash_s": imagehash.phash_simple(image), "whash ": imagehash.whash(image) }
def hash_image(image, algorithm=None): """ Hashes a given image image: Can be an URL, a path, a base64 encoded string or a PIL.Image.Image instance Erina Project — 2020\n © Anime no Sekai """ result = None has_url = False url = None log("ErinaHash", "Hashing an image...") # Needs to be a PIL instance if isfile(str(image)): image = Image.open(image) elif isinstance(image, Image.Image): image = image else: try: if base64.b64decode(str(image), validate=True): image = Image.open(BytesIO(base64.b64decode(str(image)))) else: raise ValueError("b64decode returned an empty string") except: try: url = image image = Image.open( BytesIO(requests.get(str(image)).content) ) # Open the downloaded image as a PIL Image instance has_url = True except: return HashingError( "INVALID_IMAGE_TYPE", "We couldn't convert the given image to a PIL.Image.Image instance" ) if algorithm is None: algorithm = str(config.Hash.algorithm) algorithm = str(algorithm).lower().replace(" ", "") if algorithm in ['ahash', 'a', 'averagehash', 'average']: result = imagehash.average_hash(image) elif algorithm in ['chash', 'c']: result = imagehash.colorhash(image) elif algorithm in ['dhash', 'd']: result = imagehash.dhash(image) elif algorithm in ['phash', 'p', 'perceptual', 'perceptualhash']: result = imagehash.phash(image) elif algorithm in ['wHash', 'w']: result = imagehash.whash(image) else: algorithm = algorithm.replace("_", "") if algorithm in [ 'dhashvertical', 'dvertical', 'dvert', 'verticald', 'verticaldhash' ]: result = imagehash.dhash_vertical(image) elif algorithm in [ 'phashsimple', 'psimple', 'perceptualsimple', 'simpleperceptual', 'simplep', 'simplephash', 'simpleperceptualhas' ]: result = imagehash.phash_simple(image) else: return HashingError( "INVALID_ALGORITHM", "We couldn't determine the hashing algorithm you wanted to use." ) if has_url: return HashObject(result, image, url) else: return HashObject(result, image)
def phash_s(self, img): return imagehash.phash_simple(img, hash_size=self.hash_size)
def gatherer_simple_hash(img): normal = Image.open(img).convert('L') crop=normal.crop((17,37,205,150)) hash = str(imagehash.phash_simple(crop)) return int(format(int(hash,16),'064b'))
def simple_hash(img): normal = Image.open(img).convert('L') hash = str(imagehash.phash_simple(normal)) return int(format(int(hash, 16), '064b'))
def gatherer_simple_hash(img): normal = Image.open(img).convert('L') crop = normal.crop((17, 37, 205, 150)) hash = str(imagehash.phash_simple(crop)) return int(format(int(hash, 16), '064b'))
def hashOP2(image1,lasthah): img1 = Image.fromarray(image1) hash1 = imagehash.phash_simple(img1) print(str(hash1),str(lasthah)) ham_dst = hamdist(str(hash1),str(lasthah)) return(ham_dst, hash1)
parser.add_argument("input_file") args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() # imageset = set() goodhash = {} simplehash = {} with open(args.input_file) as filelist: k = 0 print "Starting hashing of images" for line in filelist: impath = os.path.join(args.input_folder, line).strip() I = Image.open(impath) goodhash[str(imagehash.phash(I))] = impath simplehash[str(imagehash.phash_simple(I))] = impath if (k % 2000) == 0: print "Parsed item %d - good %d/%d" % (k, len(goodhash), len(simplehash)) k += 1 print "There are %d/%d unique files in the %d input images" % ( len(goodhash), len(simplehash), k) with open("hash.txt","wt") as hf: for k in goodhash.keys(): hf.write(goodhash[k]+"\n") with open("simple_hash.txt","wt") as hf: for k in simplehash.keys(): hf.write(simplehash[k]+"\n")