Ankush commited on
Commit ·
078ce08
0
Parent(s):
Initial commit — StegNet
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+10
- .gitignoreAdded+1
- README.mdAdded+100
- app.pyAdded+197
- app/__init__.pyAdded
- app/main_CLI_v1.pyAdded+75
- app/models/DEEP_STEGO/Utils/customLossWeight.pyAdded+14
- app/models/DEEP_STEGO/Utils/enhance.pyAdded+70
- app/models/DEEP_STEGO/Utils/eval.pyAdded+135
- app/models/DEEP_STEGO/Utils/preprocessing.pyAdded+18
- app/models/DEEP_STEGO/Utils/progressbarCL_animation.pyAdded+7
- app/models/DEEP_STEGO/Utils/test.pyAdded+80
- app/models/DEEP_STEGO/checkpoints/steg_model-06-0.03.hdf5Added+3
- app/models/DEEP_STEGO/hide_image.pyAdded+46
- app/models/DEEP_STEGO/models/hide.h5Added+3
- app/models/DEEP_STEGO/models/hide.h5.pngAdded
- app/models/DEEP_STEGO/models/hide.pngAdded
- app/models/DEEP_STEGO/models/model_double.pngAdded
- app/models/DEEP_STEGO/models/reveal.h5Added+3
- app/models/DEEP_STEGO/models/reveal.h5.pngAdded
- app/models/DEEP_STEGO/models/reveal.pngAdded
- app/models/DEEP_STEGO/results/input.pngAdded
- app/models/DEEP_STEGO/results/output.pngAdded
- app/models/DEEP_STEGO/reveal_image.pyAdded+45
- app/models/DEEP_STEGO/test/cover.pngAdded
- app/models/DEEP_STEGO/test/images/100098.jpgAdded
- app/models/DEEP_STEGO/test/images/101027.jpgAdded
- app/models/DEEP_STEGO/test/images/103006.jpgAdded
- app/models/DEEP_STEGO/test/images/103029.jpgAdded
- app/models/DEEP_STEGO/test/images/104010.jpgAdded
- app/models/DEEP_STEGO/test/images/105027.jpgAdded
- app/models/DEEP_STEGO/test/images/106005.jpgAdded
- app/models/DEEP_STEGO/test/images/106024.jpgAdded
- app/models/DEEP_STEGO/test/images/106025.jpgAdded
- app/models/DEEP_STEGO/test/images/106047.jpgAdded
- app/models/DEEP_STEGO/test/images/107072.jpgAdded
- app/models/DEEP_STEGO/test/images/108004.jpgAdded
- app/models/DEEP_STEGO/test/images/108041.jpgAdded
- app/models/DEEP_STEGO/test/images/108069.jpgAdded
- app/models/DEEP_STEGO/test/images/108070.jpgAdded
- app/models/DEEP_STEGO/test/images/112056.jpgAdded
- app/models/DEEP_STEGO/test/images/112082.jpgAdded
- app/models/DEEP_STEGO/test/images/113016.jpgAdded
- app/models/DEEP_STEGO/test/images/113044.jpgAdded
- app/models/DEEP_STEGO/test/images/12003.jpgAdded
- app/models/DEEP_STEGO/test/images/124084.jpgAdded
- app/models/DEEP_STEGO/test/images/126007.jpgAdded
- app/models/DEEP_STEGO/test/images/130014.jpgAdded
- app/models/DEEP_STEGO/test/images/130026.jpgAdded
- app/models/DEEP_STEGO/test/images/134008.jpgAdded
12345678910*.pth filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.hdf5 filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -textapp/ui/assets/components_backgrounds/main_window_welcome_bg.png filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.ico filter=lfs diff=lfs merge=lfs -text*.json filter=lfs diff=lfs merge=lfs -text1.idea/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100<h1 align="center"> InvisiCipher : Deep Learning-Based image Steganography with Chaotic Encryption andEnhanced Super Resolution</h1>
<p align="center"> <img src="app/ui/logo.png" alt="Project Logo" width="100"></p>
<p align="center"> <strong>Hide secrets, enhance images!</strong></p>
## Overview
Welcome to our Steganography and Super Resolution project! This project combines the power of steganography techniques and super-resolution using deep learning models. Our goal is to hide a secret image within a cover image using advanced convolutional neural networks (CNNs) and then enhance the quality of the hidden image using an Enhanced Super Resolution Generative Adversarial Network (ESRGAN). We also provide an option to encrypt the steg image using various chaos encryption algorithms for added security.
## Features
✨ **Interactive Hiding**: Utilize our intuitive hide network powered by CNNs to embed secret images within cover images effortlessly.
🔒 **Secure Encryption**: Choose from multiple chaos encryption algorithms such as AES, Blowfish to encrypt your steg image and protect your secrets.
🌟 **Enhanced Super Resolution**: Witness the magic of our ESRGAN model as it enhances the resolution and quality of the hidden image, revealing every detail.
🎨 **Easy-to-Use**: Our project provides a user-friendly interface and simple scripts to perform hiding, encryption, decryption, and image enhancement with just a few lines of code.
## Project Architecture
The project architecture consists of the following components:
1. **Prepare Network**: A CNN-based network that prepares the secret image for hiding by extracting essential features and encoding it.
2. **Hide Network**: Another CNN-based network that embeds the prepared secret image within the cover image, producing the steg image.
3. **Chaos Encryption**: Choose between AES encryption, Blowfish encryption to secure your steg image.
4. **Chaos Decryption**: Decrypt the encrypted steg image using the corresponding decryption algorithm to retrieve the steg image.
5. **Reveal Network**: A CNN-based network that extracts the secret image from the steg image by decoding the hidden information.
6. **ESRGAN**: Our Enhanced Super Resolution Generative Adversarial Network (ESRGAN) model enhances the quality and resolution of the extracted secret image.
## Getting Started
To get started with our project, follow these steps:
1. **Clone the Repository**: `git clone https://github.com/Asirwad/InvisiCipher.git`
2. **Install Dependencies**: Install the required dependencies by running `pip install -r requirements.txt`.
3. **Prepare Your Dataset**: Organize your cover and secret images dataset and place them in the appropriate directories.
4. **Customize Configuration**: Modify the configuration files to set the desired parameters for the models and encryption algorithms.
5. **Train the Models**: Run the training script to train the CNN models and ESRGAN: `python train.py`.
6. **Explore the Scripts**: Utilize the provided scripts to hide, encrypt, reveal, and enhance images based on your specific requirements.
## Welcome screen
<p align="center"> <img src="app/ui/assets/readme_assets/main_window.png" alt="Welcome" width="1000"></p>
## Image hide
<p align="center"> <img src="app/ui/assets/readme_assets/hide.png" alt="Image hide" width="1000"></p>
## Image reveal
<p align="center"> <img src="app/ui/assets/readme_assets/reveal.png" alt="Image reveal" width="1000"></p>
## Super resolution
<p align="center"> <img src="app/ui/assets/readme_assets/superres.png" alt="Super resolution" width="1000"></p>
## Contributing
We welcome contributions from the open source community. If you find any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request.
## Acknowledgements
We would like to acknowledge the following resources and libraries used in this project:
- <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2d/Tensorflow_logo.svg/1915px-Tensorflow_logo.svg.png" alt="TensorFlow" width="26" align="center"> TensorFlow: [↗️](https://www.tensorflow.org/)- <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/PyTorch_logo_icon.svg/1200px-PyTorch_logo_icon.svg.png" alt="PyTorch" width="25" align="center"> PyTorch: [↗️](https://pytorch.org/)- <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Python_and_Qt.svg/800px-Python_and_Qt.svg.png" alt="PyQt" width="25" align="center"> PyQt: [↗️](https://www.qt.io/qt-for-python)
## Contact
For any questions or inquiries, please contact us at [asirwadsali@gmail.com](mailto:asirwadsali@gmail.com).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197"""StegNet — Gradio web interface.
Entry point for HuggingFace Spaces (or any Gradio-compatible host).Set the HF_API_KEY environment variable (Spaces secret) to enablethe "Generate Image" tab.
Run locally: python app.py"""
import osimport sys
# Make sure the package root is on the path when run directlysys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import gradio as gr
from app.models.DEEP_STEGO.hide_image import hide_imagefrom app.models.DEEP_STEGO.reveal_image import reveal_imagefrom app.models.ESRGAN.upscale_image import upscale_imagefrom app.models.encryption import aes, blowfishfrom app.models.StableDiffusionAPI.StableDiffusionV2 import generate
# ---------------------------------------------------------------------------# Handler functions# ---------------------------------------------------------------------------
def hide_fn(cover, secret): if cover is None or secret is None: return None, "Please upload both a cover image and a secret image." try: output_path = hide_image(cover, secret) return output_path, "Secret image hidden successfully!" except Exception as e: return None, f"Error: {e}"
def reveal_fn(steg): if steg is None: return None, "Please upload a steg image." try: output_path = reveal_image(steg) return output_path, "Secret image revealed successfully!" except Exception as e: return None, f"Error: {e}"
def encrypt_fn(image, key, algo): if image is None: return None, "Please upload an image." if not key: return None, "Please enter a secret key." try: if algo == "AES": aes.encrypt(image, key) else: blowfish.encrypt(image, key) enc_path = image + ".enc" return enc_path, f"Image encrypted with {algo}. Download the file below." except Exception as e: return None, f"Error: {e}"
def decrypt_fn(enc_file, key, algo): if enc_file is None: return None, "Please upload an encrypted .enc file." if not key: return None, "Please enter the secret key." try: if algo == "AES": code, filename = aes.decrypt(enc_file, key) else: code, filename = blowfish.decrypt(enc_file, key) if code == -1: return None, "Decryption failed — wrong key." return filename, "Image decrypted successfully!" except Exception as e: return None, f"Error: {e}"
def upscale_fn(image): if image is None: return None, "Please upload a low-resolution image." try: output_path = upscale_image(image) return output_path, "Image upscaled 4× successfully!" except Exception as e: return None, f"Error: {e}"
def generate_fn(prompt): if not prompt or not prompt.strip(): return None, "Please enter a text prompt." if not os.environ.get("HF_API_KEY"): return None, "HF_API_KEY is not set. Add it as a Space secret to enable image generation." try: img = generate(prompt.strip()) return img, "Image generated successfully!" except Exception as e: return None, f"Error: {e}"
# ---------------------------------------------------------------------------# Gradio UI# ---------------------------------------------------------------------------
DESCRIPTION = """# StegNet### AI-Based Secure Image Steganography Platform
Hide secret images inside cover images using deep learning, encrypt the result,reveal hidden images, enhance resolution with ESRGAN, or generate new imageswith Stable Diffusion — all in one place."""
with gr.Blocks(title="StegNet", theme=gr.themes.Soft()) as demo: gr.Markdown(DESCRIPTION)
# ── Tab 1: Hide Image ────────────────────────────────────────────────── with gr.Tab("🔒 Hide Image"): gr.Markdown("Upload a **cover image** and a **secret image**. The model embeds the secret inside the cover.") with gr.Row(): cover_input = gr.Image(type="filepath", label="Cover Image") secret_input = gr.Image(type="filepath", label="Secret Image") hide_btn = gr.Button("Hide Secret", variant="primary") with gr.Row(): steg_output = gr.Image(label="Steg Image (download me)") hide_status = gr.Textbox(label="Status", interactive=False, lines=2) hide_btn.click(hide_fn, inputs=[cover_input, secret_input], outputs=[steg_output, hide_status])
# ── Tab 2: Reveal Image ──────────────────────────────────────────────── with gr.Tab("🔍 Reveal Image"): gr.Markdown("Upload a **steg image** to extract the hidden secret image.") steg_input = gr.Image(type="filepath", label="Steg Image") reveal_btn = gr.Button("Reveal Secret", variant="primary") with gr.Row(): revealed_output = gr.Image(label="Revealed Secret Image") reveal_status = gr.Textbox(label="Status", interactive=False, lines=2) reveal_btn.click(reveal_fn, inputs=[steg_input], outputs=[revealed_output, reveal_status])
# ── Tab 3: Encrypt Image ─────────────────────────────────────────────── with gr.Tab("🛡️ Encrypt Image"): gr.Markdown("Encrypt any image file (e.g. your steg image) with AES or Blowfish.") enc_image_input = gr.Image(type="filepath", label="Image to Encrypt") with gr.Row(): enc_key_input = gr.Textbox(label="Secret Key", type="password", placeholder="Enter a strong key…") enc_algo = gr.Radio(["AES", "Blowfish"], value="AES", label="Algorithm") enc_btn = gr.Button("Encrypt", variant="primary") with gr.Row(): enc_file_output = gr.File(label="Encrypted File (.enc) — Download") enc_status = gr.Textbox(label="Status", interactive=False, lines=2) enc_btn.click(encrypt_fn, inputs=[enc_image_input, enc_key_input, enc_algo], outputs=[enc_file_output, enc_status])
# ── Tab 4: Decrypt Image ─────────────────────────────────────────────── with gr.Tab("🔓 Decrypt Image"): gr.Markdown("Upload an encrypted **.enc** file and the correct key to recover the image.") dec_file_input = gr.File(label="Encrypted File (.enc)", type="filepath") with gr.Row(): dec_key_input = gr.Textbox(label="Secret Key", type="password", placeholder="Enter the key used for encryption…") dec_algo = gr.Radio(["AES", "Blowfish"], value="AES", label="Algorithm") dec_btn = gr.Button("Decrypt", variant="primary") with gr.Row(): dec_image_output = gr.Image(label="Decrypted Image") dec_status = gr.Textbox(label="Status", interactive=False, lines=2) dec_btn.click(decrypt_fn, inputs=[dec_file_input, dec_key_input, dec_algo], outputs=[dec_image_output, dec_status])
# ── Tab 5: Super Resolution ──────────────────────────────────────────── with gr.Tab("✨ Super Resolution"): gr.Markdown("Upscale any image **4×** using ESRGAN.") lr_input = gr.Image(type="filepath", label="Low-Resolution Image") upscale_btn = gr.Button("Upscale 4×", variant="primary") with gr.Row(): hr_output = gr.Image(label="High-Resolution Output") upscale_status = gr.Textbox(label="Status", interactive=False, lines=2) upscale_btn.click(upscale_fn, inputs=[lr_input], outputs=[hr_output, upscale_status])
# ── Tab 6: Generate Image ────────────────────────────────────────────── with gr.Tab("🎨 Generate Image"): gr.Markdown( "Generate an image from a text prompt using Stable Diffusion 2.1. \n" "*(Requires `HF_API_KEY` set as a Space secret.)*" ) prompt_input = gr.Textbox( label="Text Prompt", placeholder="A futuristic city at sunset, digital art…", lines=2, ) gen_btn = gr.Button("Generate", variant="primary") with gr.Row(): gen_output = gr.Image(label="Generated Image") gen_status = gr.Textbox(label="Status", interactive=False, lines=2) gen_btn.click(generate_fn, inputs=[prompt_input], outputs=[gen_output, gen_status])
demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475from tkinter import filedialog
from app.models.encryption import blowfishfrom app.models.DEEP_STEGO.hide_image import hide_imagefrom app.models.DEEP_STEGO.reveal_image import reveal_imagefrom app.models.ESRGAN.upscale_image import upscale_imagefrom app.models.encryption import aes as aes_chaos
print("StegNet CLI")
""" DEEP STEGANO """print("Image hiding")print("input the cover image filename")cover_filename = filedialog.askopenfilename(title="Select Image", filetypes=(("PNG files", "*.png"), ("JPEG files", "*.jpg;*.jpeg"), ("All files", "*.*")))print("input the secret image filename")secret_filename = filedialog.askopenfilename(title="Select Image", filetypes=(("PNG files", "*.png"), ("JPEG files", "*.jpg;*.jpeg"), ("All files", "*.*")))hide_image(cover_filename, secret_filename)
print("image hidden successfully\n\n")
print("1. AES")print("2. Blowfish")enc_choice = int(input("What type of encryption do you want? :"))print("Your choice is : ", enc_choice)
if enc_choice == 1: # AES Encryption filename = filedialog.askopenfilename(title="Select Image", filetypes=( ("PNG files", "*.png"), ("JPEG files", "*.jpg;*.jpeg"), ("All files", "*.*"))) key = input("Enter your secret key : ") aes_chaos.encrypt(filename, key)
# AES Decryption print("AES Decryption") key = input("Enter your secret key : ") filename = filedialog.askopenfilename(title="Select Image", filetypes=( ("All files", "*.*"), ("JPEG files", "*.jpg;*.jpeg"), ("PNG files", "*.png"))) aes_chaos.decrypt(filename, key)
elif enc_choice == 2: print("Blowfish Encryption") # Blowfish Encryption key = input("Enter your secret key : ") filename = filedialog.askopenfilename(title="Select Image", filetypes=( ("PNG files", "*.png"), ("JPEG files", "*.jpg;*.jpeg"), ("All files", "*.*"))) blowfish.encrypt(filename, key) print("Encrypted output saved to output_encrypted.png")
# Blowfish Decryption filename = filedialog.askopenfilename(title="Select Image", filetypes=( ("PNG files", "*.png"), ("JPEG files", "*.jpg;*.jpeg"), ("All files", "*.*"))) key = input("Enter your secret key : ") blowfish.decrypt(filename, key)
else: print('Invalid choice')
print("input the steg image filename")steg_filename = filedialog.askopenfilename(title="Select Image", filetypes=( ("PNG files", "*.png"), ("JPEG files", "*.jpg;*.jpeg"), ("All files", "*.*")))reveal_image(steg_filename)
""" UP-SCALING """print("UP-SCALING")print("input the low res image filename")low_res_filename = filedialog.askopenfilename(title="Select Image", filetypes=( ("PNG files", "*.png"), ("JPEG files", "*.jpg;*.jpeg"), ("All files", "*.*")))upscale_image(low_res_filename)
1234567891011121314from tensorflow.keras.losses import mean_squared_error
# Loss functionsdef custom_loss_1(secret, secret_pred): # Compute L2 loss(MSE) for secret image secret_mse = mean_squared_error(secret, secret_pred) return secret_mse
def custom_loss_2(cover, cover_predict): # Compute L2 loss(MSE) for cover image cover_mse = mean_squared_error(cover, cover_predict) return cover_mse12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import numpy as npimport argparseimport sysimport mathfrom PIL import ImageFilter, Imageimport cv2
'''Enhance video by applying denoise and sharpen filters'''
# Construct argument parserparser = argparse.ArgumentParser(description='Use block shuffle')parser.add_argument('--denoise', action='store_true', default=False)parser.add_argument('--sharpen', action='store_true', default=False)parser.add_argument("--input_video", required=True, help="path to input video")args = vars(parser.parse_args())
# Start video enhancementprint('\nEnhancing video ...\n')
# Update progress bardef update_progress(current_frame, total_frames): progress = math.ceil((current_frame / total_frames) * 100) sys.stdout.write('\rProgress: [{0}] {1}%'.format('>' * math.ceil(progress / 10), progress))
# Open the input videovid_cap = cv2.VideoCapture(args['input_video'])
# Total input video framesnum_frames = int(vid_cap.get(cv2.CAP_PROP_FRAME_COUNT))print("Total frames in input video:", num_frames)
# Initialize the video writerenhanced_video = cv2.VideoWriter('results/enhanced_secret_300.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 15, (300, 300))
# Initialize the frame bufferframes = []
# Load the frames to bufferwhile vid_cap.isOpened(): success, image = vid_cap.read() if success: frames.append(image) else: break
# Set up the start frame indexstart_frame = 5
# Enhance and save video frame-by-framefor i in range(start_frame, len(frames) - (start_frame + 1)): output = frames[i] if args["denoise"]: output = cv2.fastNlMeansDenoisingColoredMulti(frames, i, 11) if args["sharpen"]: output = np.array(Image.fromarray(output).filter(ImageFilter.DETAIL)) enhanced_video.write(output) update_progress(i, num_frames - (start_frame + 1))
# Finish video enhancementprint('\n\nSuccessfully enhanced video !!!\n')
'''Sample run:-python enhance.py --input_video results/secret_outvid_300.avi --denoise --sharpen'''123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135import numpy as npimport randomimport globimport sysimport osfrom PIL import Imageimport matplotlib.pyplot as pltfrom tensorflow.keras.losses import mean_squared_errorfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras.models import load_modelfrom pathlib import Path
'''Evaluates the trained model on a new datasetUses Mean Square Error as evaluation metric'''
# Path for evaluation datasetEVAL_PATH = Path(sys.argv[1]).resolve()BATCH_SIZE = 1TEST_NUM = len(glob.glob(str(EVAL_PATH)))
# Normalize input for evaluationdef normalize_batch(imgs): return (imgs - np.array([0.485, 0.456, 0.406])) / np.array([0.229, 0.224, 0.225])
# Denormalize output for predictiondef denormalize_batch(imgs, should_clip=True): imgs = (imgs * np.array([0.229, 0.224, 0.225])) + np.array([0.485, 0.456, 0.406])
if should_clip: imgs = np.clip(imgs, 0, 1) return imgs
# Create a data generator for evaluationtest_imgen = ImageDataGenerator(rescale=1. / 255)
# Compute L2 loss(MSE) for secret imagedef custom_loss_1(secret, secret_pred): secret_mse = mean_squared_error(secret, secret_pred) return secret_mse
# Compute L2 loss(MSE) for cover imagedef custom_loss_2(cover, cover_pred): cover_mse = mean_squared_error(cover, cover_pred) return cover_mse
# Load the trained modelmodel = load_model(sys.argv[2], custom_objects={'custom_loss_1': custom_loss_1, 'custom_loss_2': custom_loss_2})
# Custom data generatordef generate_generator_multiple(generator, direc): genX1 = generator.flow_from_directory(direc, target_size=(224, 224), batch_size=12, shuffle=True, seed=3, class_mode=None) genX2 = generator.flow_from_directory(direc, target_size=(224, 224), batch_size=12, shuffle=True, seed=8, class_mode=None)
while True: X1i = normalize_batch(genX1.next()) X2i = normalize_batch(genX2.next())
yield ({'secret': X1i, 'cover': X2i}, {'hide_conv_f': X2i, 'revl_conv_f': X1i}) # Yield both images and their mutual label
# Load data using generatortestgenerator = generate_generator_multiple(test_imgen, direc=str(EVAL_PATH.parent))
# Evaluates the model using data generatorscore = model.evaluate(testgenerator, steps=TEST_NUM / BATCH_SIZE, verbose=0)
# Print mean square errorprint('Mean square error:', score[0])
'''Test the model on a random pair of images (test)Plots the input and output for verification'''
# Perform prediction for single inputdef predict(source, cover): # Normalize inputs secret = np.array(source / 255.0) cover = np.array(cover / 255.0)
# Predict output coverout, secretout = model.predict( [normalize_batch(np.reshape(secret, (1, 224, 224, 3))), normalize_batch(np.reshape(cover, (1, 224, 224, 3)))])
# Postprocess output cover image coverout = denormalize_batch(coverout) coverout = np.squeeze(coverout) * 255.0 coverout = np.uint8(coverout)
# Postprocess output secret image secretout = denormalize_batch(secretout) secretout = np.squeeze(secretout) * 255.0 secretout = np.uint8(secretout)
# Plot output images fig_out, ax_out = plt.subplots(1, 2, figsize=(10, 10)) fig_out.suptitle('Outputs') ax_out[0].title.set_text("Secret output") ax_out[0].imshow(secretout) ax_out[1].title.set_text("Cover output") ax_out[1].imshow(coverout) print("Prediction Completed!")
# Load random test image pairssec, cov = random.sample(os.listdir(str(EVAL_PATH)), k=2)
source = np.array(Image.open(str(EVAL_PATH) + '/' + sec))cover = np.array(Image.open(str(EVAL_PATH) + '/' + cov))
# Plot input imagesfig_in, ax_in = plt.subplots(1, 2, figsize=(10, 10))fig_in.suptitle('Inputs')ax_in[0].title.set_text("Secret input")ax_in[0].imshow(source)ax_in[1].title.set_text("Cover input")ax_in[1].imshow(cover)
# Perform predictionpredict(source, cover)
# Sample run: python eval.py dataset/eval_data checkpoints/steg_model-06-0.03.hdf5123456789101112131415161718import numpy as np
# Preprocessing functionsdef normalize_batch(images): """Performs channel-wise z-score normalization"""
return (images - np.array([0.485, 0.456, 0.406])) / np.array([0.229, 0.224, 0.225])
def denormalize_batch(images, should_clip=True): """Denormalize the images for prediction"""
images = (images * np.array([0.229, 0.224, 0.225])) + np.array([0.485, 0.456, 0.406])
if should_clip: images = np.clip(images, 0, 1) return images1234567import mathimport sys
def update_progress(current_frame, total_frames): progress = math.ceil((current_frame/total_frames)*100) sys.stdout.write('\rProgress: [{0}] {1}%'.format('>'*math.ceil(progress/10), progress))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import numpy as npimport sysfrom tensorflow.keras.models import Modelfrom tensorflow.keras.utils import plot_modelfrom tensorflow.keras.models import load_modelfrom PIL import Imageimport matplotlib.pyplot as pltfrom random import randintimport imageiofrom skimage.util.shape import view_as_blocks
'''Test the model on sample images (unseen)Plot the input and output images'''
# Load test imagestest_images = np.load(sys.argv[1])
# Load modelmodel = load_model(sys.argv[2], compile=False)
# Normalize inputsdef normalize_batch(imgs): """ Performs channel-wise z-score normalization """
return (imgs - np.array([0.485, 0.456, 0.406])) / np.array([0.229, 0.224, 0.225])
# Denormalize outputsdef denormalize_batch(imgs, should_clip=True): imgs = (imgs * np.array([0.229, 0.224, 0.225])) + np.array([0.485, 0.456, 0.406])
if should_clip: imgs = np.clip(imgs, 0, 1) return imgs
# Load images as batch (batch size -4)secretin = test_images[np.random.choice(len(test_images), size=4, replace=False)]coverin = test_images[np.random.choice(len(test_images), size=4, replace=False)]
# Perform batch predictioncoverout, secretout = model.predict([normalize_batch(secretin), normalize_batch(coverin)])
# Postprocess cover outputcoverout = denormalize_batch(coverout)coverout = np.squeeze(coverout) * 255.0coverout = np.uint8(coverout)
# Postprocess secret outputsecretout = denormalize_batch(secretout)secretout = np.squeeze(secretout) * 255.0secretout = np.uint8(secretout)
# Convert images to UINT8 format (0-255)coverin = np.uint8(np.squeeze(coverin * 255.0))secretin = np.uint8(np.squeeze(secretin * 255.0))
# Plot the imagesdef plot(im, title): fig = plt.figure(figsize=(20, 20))
for i in range(4): sub = fig.add_subplot(1, 4, i + 1) sub.title.set_text(title + " " + str(i + 1)) sub.imshow(im[i, :, :, :])
# Plot secret input and outputplot(secretin, "Secret Input")plot(secretout, "Secret Output")
# Plot cover input and outputplot(coverin, "Cover Input")plot(coverout, "Cover Output")
# Sample run: python test.py test/testdata.npy checkpoints/steg_model-06-0.03.hdf5123version https://git-lfs.github.com/spec/v1oid sha256:d2567ad658864875aba9f3c51fde8e2b032d4964b1382298e2d36c62708adcebsize 3211552012345678910111213141516171819202122232425262728293031323334353637383940414243444546import osimport tempfileimport numpy as npfrom tensorflow.keras.models import load_modelfrom PIL import Imageimport imageiofrom app.models.DEEP_STEGO.Utils.preprocessing import normalize_batch, denormalize_batch
_MODEL_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models', 'hide.h5')_model = None
def _get_model(): global _model if _model is None: _model = load_model(_MODEL_PATH) return _model
def hide_image(cover_image_filepath, secret_image_filepath): model = _get_model()
secret_image_in = Image.open(secret_image_filepath).convert('RGB') cover_image_in = Image.open(cover_image_filepath).convert('RGB')
if secret_image_in.size != (224, 224): secret_image_in = secret_image_in.resize((224, 224)) if cover_image_in.size != (224, 224): cover_image_in = cover_image_in.resize((224, 224))
secret_image_in = np.array(secret_image_in).reshape(1, 224, 224, 3) / 255.0 cover_image_in = np.array(cover_image_in).reshape(1, 224, 224, 3) / 255.0
steg_image_out = model.predict([normalize_batch(secret_image_in), normalize_batch(cover_image_in)])
steg_image_out = denormalize_batch(steg_image_out) steg_image_out = np.squeeze(steg_image_out) * 255.0 steg_image_out = np.uint8(steg_image_out)
_, output_path = tempfile.mkstemp(suffix='.png') imageio.imsave(output_path, steg_image_out) print("Saved steg image to", output_path)
return output_path
123version https://git-lfs.github.com/spec/v1oid sha256:d134911e755c063b31d1f2f76678a2b690c5952536bb7c01981cdf6d68e3724bsize 7692752123version https://git-lfs.github.com/spec/v1oid sha256:f60e937b2957601be10e58df12aaa27b51763449a7883baaf50613500c2dfb32size 3102992123456789101112131415161718192021222324252627282930313233343536373839404142434445import osimport tempfileimport numpy as npfrom tensorflow.keras.models import load_modelfrom PIL import Imageimport imageiofrom app.models.DEEP_STEGO.Utils.preprocessing import normalize_batch, denormalize_batch
_MODEL_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models', 'reveal.h5')_model = None
def _get_model(): global _model if _model is None: _model = load_model(_MODEL_PATH, compile=False) return _model
def reveal_image(stego_image_filepath): model = _get_model()
stego_image = Image.open(stego_image_filepath).convert('RGB')
if stego_image.size != (224, 224): stego_image = stego_image.resize((224, 224))
stego_image = np.array(stego_image).reshape(1, 224, 224, 3) / 255.0
secret_image_out = model.predict([normalize_batch(stego_image)])
secret_image_out = denormalize_batch(secret_image_out) secret_image_out = np.squeeze(secret_image_out) * 255.0 secret_image_out = np.uint8(secret_image_out)
_, output_path = tempfile.mkstemp(suffix='.png') imageio.imsave(output_path, secret_image_out) print("Saved revealed image to", output_path)
return output_path
.gitattributesAdded+10
.gitignoreAdded+1
README.mdAdded+100
app.pyAdded+197
app/__init__.pyAdded
app/main_CLI_v1.pyAdded+75
app/models/DEEP_STEGO/Utils/customLossWeight.pyAdded+14
app/models/DEEP_STEGO/Utils/enhance.pyAdded+70
app/models/DEEP_STEGO/Utils/eval.pyAdded+135
app/models/DEEP_STEGO/Utils/preprocessing.pyAdded+18
app/models/DEEP_STEGO/Utils/progressbarCL_animation.pyAdded+7
app/models/DEEP_STEGO/Utils/test.pyAdded+80
app/models/DEEP_STEGO/checkpoints/steg_model-06-0.03.hdf5Added+3
app/models/DEEP_STEGO/hide_image.pyAdded+46
app/models/DEEP_STEGO/models/hide.h5Added+3
app/models/DEEP_STEGO/models/hide.h5.pngAdded

Large File Pointer Details
- SHA256: b6a735df67b3ed400e1f06afe00c720854009be16485bd10e097f0e3f3454907
- Pointer size: 131 Bytes
- Size of remote file: 296 kB
app/models/DEEP_STEGO/models/hide.pngAdded

Large File Pointer Details
- SHA256: baa31d7b892d31277236c656e697efe4e5bd611b7b52bd77c3c34d8e2aacc8ee
- Pointer size: 130 Bytes
- Size of remote file: 90.7 kB
app/models/DEEP_STEGO/models/model_double.pngAdded

Large File Pointer Details
- SHA256: 7d8e68c06aa466bf2eff36cb94748a818d7dfaf995ff8ded38c1d33e88be91b7
- Pointer size: 131 Bytes
- Size of remote file: 138 kB
app/models/DEEP_STEGO/models/reveal.h5Added+3
app/models/DEEP_STEGO/models/reveal.h5.pngAdded

Large File Pointer Details
- SHA256: acd1faad8493abec5bf2542e4c923c4c701813102fbf1efada5cfd7c4092575e
- Pointer size: 131 Bytes
- Size of remote file: 147 kB
app/models/DEEP_STEGO/models/reveal.pngAdded

Large File Pointer Details
- SHA256: 56c54e864c5edeebd013aa055f98b5a9b862c984070e76990257d01faf4ce6b7
- Pointer size: 130 Bytes
- Size of remote file: 49.7 kB
app/models/DEEP_STEGO/results/input.pngAdded

Large File Pointer Details
- SHA256: f2fdb45cf2a205da6f29d70c751ce6199962aaec0ba1c8dace1dadde4006d57f
- Pointer size: 131 Bytes
- Size of remote file: 189 kB
app/models/DEEP_STEGO/results/output.pngAdded

Large File Pointer Details
- SHA256: b65181d36680559b4b972988e9eb3f360552578e754be2e13f42f173c26376df
- Pointer size: 131 Bytes
- Size of remote file: 204 kB
app/models/DEEP_STEGO/reveal_image.pyAdded+45
app/models/DEEP_STEGO/test/cover.pngAdded

Large File Pointer Details
- SHA256: 2e61384130327a4fdcd0c5e32ebc663a3fd447723758c8d521cd6a7bf48ada1a
- Pointer size: 130 Bytes
- Size of remote file: 78.4 kB
app/models/DEEP_STEGO/test/images/100098.jpgAdded

Large File Pointer Details
- SHA256: 4cc3ebc05afee168371c68cd61801bc4b7a6c978dea7ec8361b6e661f56196bc
- Pointer size: 130 Bytes
- Size of remote file: 30 kB
app/models/DEEP_STEGO/test/images/101027.jpgAdded

Large File Pointer Details
- SHA256: 02071459ecc3928b59e21a2bd9df94cdde3bb41104b4e5623cc0727189dcd562
- Pointer size: 130 Bytes
- Size of remote file: 23.3 kB
app/models/DEEP_STEGO/test/images/103006.jpgAdded

Large File Pointer Details
- SHA256: 1eecbd3b2fcd55086a6bff68815985d6138358ce70613962f87eee25060acac6
- Pointer size: 130 Bytes
- Size of remote file: 26.2 kB
app/models/DEEP_STEGO/test/images/103029.jpgAdded

Large File Pointer Details
- SHA256: 2582b16c2d10eff539ba50ba5bd5eb7ff80a110ae55b0dfc682ef73748e74d8c
- Pointer size: 130 Bytes
- Size of remote file: 15.9 kB
app/models/DEEP_STEGO/test/images/104010.jpgAdded

Large File Pointer Details
- SHA256: 7a243cafa4dbedbea5c2bde392e05b7c557a957b84751e87b6742ee93ff5c7f6
- Pointer size: 130 Bytes
- Size of remote file: 25.3 kB
app/models/DEEP_STEGO/test/images/105027.jpgAdded

Large File Pointer Details
- SHA256: 1fd0e01544e30b1467c58d3c11badb72baa4eab6d250856dd0e42a11fd4866f7
- Pointer size: 130 Bytes
- Size of remote file: 19.9 kB
app/models/DEEP_STEGO/test/images/106005.jpgAdded

Large File Pointer Details
- SHA256: f5ee139c1bdf32d613d9cf5d0b4a066e9fbc983222e2d172859f0cdd96b78db2
- Pointer size: 130 Bytes
- Size of remote file: 14.3 kB
app/models/DEEP_STEGO/test/images/106024.jpgAdded

Large File Pointer Details
- SHA256: b86b343843d811f5ea8e19df32eea9b551a27fb1e1b5a0b146c030721f2966e7
- Pointer size: 130 Bytes
- Size of remote file: 13.7 kB
app/models/DEEP_STEGO/test/images/106025.jpgAdded

Large File Pointer Details
- SHA256: e8406b68383086a77a40f7474f2e8f743b724a96f50357b322182dd86965d8c3
- Pointer size: 130 Bytes
- Size of remote file: 10.4 kB
app/models/DEEP_STEGO/test/images/106047.jpgAdded

Large File Pointer Details
- SHA256: 6b116cad8437cace1d892d3797e90a250c84fff53285945d3eeb8d8beb6f9b31
- Pointer size: 130 Bytes
- Size of remote file: 17.1 kB
app/models/DEEP_STEGO/test/images/107072.jpgAdded

Large File Pointer Details
- SHA256: 88d330d4cd64dab5bc2a05f7092aae3d5359ff17566c7fc52f22537b4d46d315
- Pointer size: 130 Bytes
- Size of remote file: 25 kB
app/models/DEEP_STEGO/test/images/108004.jpgAdded

Large File Pointer Details
- SHA256: 7a3c2a8cfaeded0657eaf509a35275b8831466ec1483e821dc7a3689a65e3c4b
- Pointer size: 130 Bytes
- Size of remote file: 27.8 kB
app/models/DEEP_STEGO/test/images/108041.jpgAdded

Large File Pointer Details
- SHA256: a1a8bb4a8f189e00c7ba0c3333747ab00177f9c4da12e38eff7d44136e1b0fbd
- Pointer size: 130 Bytes
- Size of remote file: 21 kB
app/models/DEEP_STEGO/test/images/108069.jpgAdded

Large File Pointer Details
- SHA256: 64105352e2f31f253464ac00646c43e4cfc8519a20459b1bc202e4c6e8c3ffdc
- Pointer size: 130 Bytes
- Size of remote file: 26.7 kB
app/models/DEEP_STEGO/test/images/108070.jpgAdded

Large File Pointer Details
- SHA256: 15b38de0141ebdfb3e24cb3f3090509d0deca82c63bfe9c97fbf493a41aba7a7
- Pointer size: 130 Bytes
- Size of remote file: 27.5 kB
app/models/DEEP_STEGO/test/images/112056.jpgAdded

Large File Pointer Details
- SHA256: 3f78f2e76baca8129938b7c8d9c71b8aace2f4c4d600a9d969bfcd025af519fc
- Pointer size: 130 Bytes
- Size of remote file: 13.8 kB
app/models/DEEP_STEGO/test/images/112082.jpgAdded

Large File Pointer Details
- SHA256: d44830f2108ba022bb4aeb93369e7970c4704718107277546072b579c1a425a6
- Pointer size: 130 Bytes
- Size of remote file: 24.3 kB
app/models/DEEP_STEGO/test/images/113016.jpgAdded

Large File Pointer Details
- SHA256: d06addf6d5fefc012d6b08d2bd92f962bf2dab91a5317d7ceaee49d466d1c367
- Pointer size: 130 Bytes
- Size of remote file: 27.5 kB
app/models/DEEP_STEGO/test/images/113044.jpgAdded

Large File Pointer Details
- SHA256: 590f8063a1177764f49390c2baca8e023b3846e11bcbe14e488813379852d503
- Pointer size: 130 Bytes
- Size of remote file: 27.4 kB
app/models/DEEP_STEGO/test/images/12003.jpgAdded

Large File Pointer Details
- SHA256: b2899a821588a3313434d3c4d85320d419534f151414c5d039754fb279208d65
- Pointer size: 130 Bytes
- Size of remote file: 26.6 kB
app/models/DEEP_STEGO/test/images/124084.jpgAdded

Large File Pointer Details
- SHA256: a291fc736acc5bc64544dfca7d9728c810eeacc03c26acd0153f9389bfb785af
- Pointer size: 130 Bytes
- Size of remote file: 21.3 kB
app/models/DEEP_STEGO/test/images/126007.jpgAdded

Large File Pointer Details
- SHA256: 77da911c10894c83e0687d73a8f15a1a0a8baf96762454cd3cf5693e087c99ad
- Pointer size: 130 Bytes
- Size of remote file: 17.8 kB
app/models/DEEP_STEGO/test/images/130014.jpgAdded

Large File Pointer Details
- SHA256: d216637fc4bbaaecaf2120e4e295f7938049fd41140b9b8556520d50a5aa6630
- Pointer size: 130 Bytes
- Size of remote file: 19.4 kB
app/models/DEEP_STEGO/test/images/130026.jpgAdded

Large File Pointer Details
- SHA256: da1ef567d4418d823d5dd0c0400a58a8323a948c0c5f9c63303af48224c17a13
- Pointer size: 130 Bytes
- Size of remote file: 23.6 kB
app/models/DEEP_STEGO/test/images/134008.jpgAdded

Large File Pointer Details
- SHA256: a5669969f9328a20804ad0b25a1e5a49f70527125218c4c49c9d89eef620cf81
- Pointer size: 130 Bytes
- Size of remote file: 18.2 kB