I2NeT 2.3
I2NeT (Images to Network Traffic), extract and reconstruct data from RGB-encoded PNG images into CSV format. Suitable for CNN-based anomaly detection.
Requires Python: >=3.9

# I2NeT (Image to Network) 🖼️ ➡️ 📊

**I2NeT** is the reverse companion to [NeT2I](https://github.com/omeshF/NeT2I). It decodes RGB images created from network traffic data back into structured tabular form. This enhanced version supports both IPv4 and IPv6 network data with intelligent adaptive decoding.

> 🧩 **Important**: I2NeT decodes only the format output by [NeT2I](https://github.com/omeshF/NeT2I). Images from other tools will not decode correctly.

## ✨ Features

- 🔁 **Bi-directional Processing**: Reverses RGB images generated by NeT2I into CSV-format network traffic data
- 🌐 **Dual IP Support**: Handles both IPv4 and IPv6 network addresses seamlessly
- 🧠 **Adaptive Decoding**: Automatically detects data structure and adjusts decoding strategy
- 🎯 **Smart Type Detection**: Uses filename prefixes (`ipv4_`, `ipv6_`) for automatic protocol detection
- 💡 **Comprehensive Data Types**:
  - IPv4 addresses (4 octets from 8 RGB pixels)
  - IPv6 addresses (16 bytes from 6 RGB pixels)
  - MAC addresses (6 bytes from 4 RGB pixels)
  - Integers and floats (IEEE 754 from 2 RGB pixels)
  - Strings (via consistent hash representations)
- 🔧 **Flexible Configuration**: Supports separate type definitions for IPv4 and IPv6
- 📊 **Batch Processing**: Handles multiple image sets with progress tracking
- 🛡️ **Error Resilience**: Graceful handling of incomplete or corrupted data

## 📋 Requirements

- **Python 3.9+**
- **Dependencies**:
  - Pillow
  - NumPy
  - Standard library modules (struct, json, csv, glob, ipaddress)

## 🚀 Installation

```bash
# Install required dependencies
pip install pillow numpy

# Clone the repository
git clone https://github.com/omeshF/I2NeT.git
cd I2NeT
```

## 📁 Directory Structure

Organize your PNG images with proper naming conventions:

```
data/
├── ipv4_0.png          # IPv4 data images
├── ipv4_1.png
├── ipv4_2.png
├── ipv6_0.png          # IPv6 data images  
├── ipv6_1.png
├── ipv6_2.png
├── data_types.json     # IPv4 type definitions (optional)
└── data_types_ipv6.json # IPv6 type definitions (optional)
```

## 🎯 Usage

### Basic Usage

```python
import I2NeT.decoder as decoder

# Decode all images in directory
results = decoder.decode(
    data_directory='data',
    output_csv='decoded_network_data.csv'
)

print(f"✅ Processed {results['total_images_processed']} images")
print(f"📊 Generated {results['total_rows']} data rows")
```

### Advanced Configuration

```python
import I2NeT.decoder as decoder

# Custom configuration with separate type files
results = decoder.decode(
    data_directory='network_images',
    output_csv='reconstructed_data.csv',
    types_file_ipv4='ipv4_schema.json',
    types_file_ipv6='ipv6_schema.json',
    verbose=True
)

# Access detailed breakdown
print(f"IPv4 rows: {results['ipv4_rows']}")
print(f"IPv6 rows: {results['ipv6_rows']}")
print(f"Success: {results['success']}")
```

### Single Image Decoding

```python
import I2NeT.decoder as decoder

# Decode individual image
values = decoder.decode_single(
    image_path='data/ipv6_0.png',
    is_ipv6=True
)
print(f"Decoded values: {values}")

# Auto-detect from filename
values = decoder.decode_single('data/ipv4_5.png')  # Auto-detects IPv4
```

### Using the Enhanced Decoder Class

```python
from I2NeT.decoder import EnhancedI2NeT_Decoder

# Create decoder instance
decoder = EnhancedI2NeT_Decoder(
    types_file_ipv4='data_types.json',
    types_file_ipv6='data_types_ipv6.json'
)

# Process different datasets
results = decoder.load_data('network_captures', verbose=True)

# Decode specific image
reconstructed = decoder.decode_single_image('capture_001.png', is_ipv6=False)
```

## 🔍 Decoding Logic

| Data Type | Storage Method | Decoding Process |
|-----------|----------------|------------------|
| **Float/Integer** | 2 RGB pixels (6 bytes) | IEEE 754 float extraction |
| **IPv4 Address** | 8 RGB pixels (4 octets × 2 pixels) | 4 floats → 4 octets → dotted decimal |
| **IPv6 Address** | 6 RGB pixels (18 bytes) | 16 bytes → IPv6 address object |
| **MAC Address** | 4 RGB pixels (2 chunks × 2 pixels) | 2 floats → hex chunks → colon notation |
| **String** | 2 RGB pixels | Hash value → string representation |

### Adaptive Decoding Features

- **Truncation Handling**: Gracefully processes incomplete data by treating remaining pixels as floats
- **Type Detection**: Automatically determines data structure from available RGB pixel count  
- **Fallback Strategy**: Uses generic float decoding when type information is unavailable
- **Mixed Protocol Support**: Handles datasets containing both IPv4 and IPv6 addresses

## 📊 Output Files

| File | Description |
|------|-------------|
| `decoded_network_data.csv` | Final merged output with all decoded data |
| `data_types.json` | IPv4 type schema (optional) |
| `data_types_ipv6.json` | IPv6 type schema (optional) |

## 🛠️ Type Definition Files

Create JSON files to guide the decoding process:

**data_types.json** (IPv4):
```json
{
  "original_types": ["IPv4 Address", "MAC Address", "Integer", "Float"],
  "final_types": ["IPv4 Address", "IPv4 Address", "IPv4 Address", "IPv4 Address", "MAC Address", "MAC Address", "Integer", "Float"]
}
```

**data_types_ipv6.json** (IPv6):
```json
{
  "original_types": ["IPv6 Address", "MAC Address", "Float"],
  "final_types": ["IPv6 Address", "MAC Address", "MAC Address", "Float"]
}
```

## ⚡ Performance & Compatibility

- **Multi-format Support**: PNG, JPG, JPEG, BMP, TIFF
- **Batch Processing**: Progress tracking for large datasets
- **Memory Efficient**: Processes images sequentially to minimize memory usage
- **Error Recovery**: Continues processing even if individual images fail

## 🚨 Important Notes

1. **NeT2I Compatibility**: Only works with images generated by [NeT2I](https://github.com/omeshF/NeT2I)
2. **Filename Conventions**: Use `ipv4_` and `ipv6_` prefixes for automatic protocol detection
3. **Type Files**: Optional but recommended for accurate IP and MAC address reconstruction
4. **Image Order**: Files are sorted numerically when possible, alphabetically otherwise

## 🎯 Use Cases

This enhanced I2NeT decoder is ideal for:

- **Network Security Analysis**: Reconstructing network traffic from image-encoded datasets
- **Machine Learning Workflows**: Converting CNN-processed network images back to structured data
- **Data Integrity Verification**: Validating image-encoded datasets before training
- **Mixed Protocol Datasets**: Handling modern networks with both IPv4 and IPv6 traffic
- **Forensic Analysis**: Recovering network data from visual representations

## 📚 API Reference

### Main Functions

- `decode(data_directory, output_csv, ...)` - Main decoding function
- `decode_single(image_path, ...)` - Single image decoder
- `load_data_with_ipv4_ipv6_support(...)` - Enhanced loader with dual IP support
- `get_decoder(...)` - Factory function for decoder instances

### Classes

- `EnhancedI2NeT_Decoder` - Main decoder class with advanced features

## 📖 Citation

If you use I2NeT or NeT2I in your research, please cite:

```bibtex
@inproceedings{fernando2023new,
  title={New algorithms for the detection of malicious traffic in 5g-mec},
  author={Fernando, Omesh A and Xiao, Hannan and Spring, Joseph},
  booktitle={2023 IEEE Wireless Communications and Networking Conference (WCNC)},
  pages={1--6},
  year={2023},
  organization={IEEE}
}
```

## 👥 Authors

- **Omesh Fernando** 

## 📄 License

This project is licensed under the MIT License.

---

🔗 **Related Project**: [NeT2I](https://github.com/omeshF/NeT2I) - Convert network data to images