Skip to content

Instantly share code, notes, and snippets.

@sandeshbhusal
Last active September 11, 2020 01:19
Show Gist options
  • Save sandeshbhusal/fe027ef63abf6bec9c323fb5a43ef319 to your computer and use it in GitHub Desktop.
Save sandeshbhusal/fe027ef63abf6bec9c323fb5a43ef319 to your computer and use it in GitHub Desktop.
import numpy as np
import pandas as pd
from scipy.ndimage.interpolation import shift
import cv2
from matplotlib import pyplot as plt
input_photo_path = "/kaggle/input/84474892_2612930752149692_1911641796866211840_o.jpg"
image = cv2.imread(input_photo_path)
# Fix color expression. Plt uses RGB, cv2 reads BGR
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = image.astype(np.uint8)
plt.imshow(image)
# Split into r, g, b channels
r, g, b = cv2.split(image)
# Move a random amount of distance from center of image
MAX_GLITCH_OFFSET = int(0.05 * min(image.shape[0], image.shape[1]))
dr = random.randint(0, MAX_GLITCH_OFFSET)
dg = random.randint(0, MAX_GLITCH_OFFSET)
db = random.randint(0, MAX_GLITCH_OFFSET)
# Move the image.
r = shift(r, dr, cval = 0)
g = shift(g, dg, cval = 0)
b = shift(b, db, cval = 0)
glitched = cv2.merge([r, g, b])
plt.imshow(glitched)
# Let's encode a secret message for our birthday boy!
# How many characters do I get per layer? I'll just use the horizontal space for now, not vertical :)
charLimitR = dr * image.shape[0]
charLimitG = dg * image.shape[0]
charLimitB = db * image.shape[0]
messageR = "FIND THIS YOURSELF"
messageG = "THIS ONE TOO"
messageB = "AND FINALLY THIS"
# Let's create a matrix to hold all our bytes!
mat = np.zeros_like(glitched)
messages = [messageR, messageG, messageB]
layers = cv2.split(glitched) # Maybe we can do better. in a hurry right now tho :P
package = zip(messages, layers)
final_with_message = []
for message, layer in package:
message_to_add = [ord(ch) for ch in message]
paddings = [0] * (image.shape[0] * image.shape[1] - len(message_to_add))
message_to_add += paddings
print(message_to_add[:200])
# Reshape our message.
reshaped_message = np.array(message_to_add).reshape(layer.shape)
reshaped_message = reshaped_message.astype(np.uint8)
# Add this to the channel!!
layer += reshaped_message
final_with_message.append(layer)
print(layer.size)
# Recombine the glitched image.
final_with_message = cv2.merge(final_with_message)
final_with_message.shape
plt.imshow(final_with_message)
cv2.imwrite('pranjal_glitched.png', final_with_message)
plt.imshow(final_with_message)
# Check if we get the same bytes from the image back!
r, g, b = cv2.split(final_with_message)
r = r.reshape(r.shape[0] * r.shape[1])
print(r[:200])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment