Steve Chan bio photo

Steve Chan

Artificial Intelligence,
Machine Learning,
Numerical Algorithms,
Numerical Methods,
Hyper-Heuristics,
Metaheuristics,
Data Analytics,
Information Science,
Decision Science

Twitter GitHub GitLab Website E-Mail

Experimentation Scripts for AG #15

So that reviewers and readers can reproduce the results for this IEEE paper, please find the "Experimentation Scripts for AG #15" in Python, Go (Golang), and Rust below (rather than in the paper):

Python Script for AG #15

(as referenced in Section IIIC. Experimentation)

Prospective Efficacy Value-added Proposition: Front-loaded scene lock.



import random
import numpy as np
from PIL import Image
from diffusers import StableDiffusionInpaintPipeline
import torch

# Configuration
MODEL_ID = "runwayml/stable-diffusion-inpainting"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# Prompt
PROMPT = """
This is an image editing task. Preserve the scene exactly.

The output must remain visually identical to the input image.
Preserve at least 99% of the original pixels and keep all objects,
textures, materials, lighting, shadows, perspective, and geometry unchanged.

Perform a copy of the image and apply only a tiny localized modification.

Inside the selected region introduce exactly one subtle early-stage wiring anomaly,
such as minor insulation abrasion, a single exposed conductor strand,
a small insulation crack, slight overheating discoloration,
or minor connector looseness.
"""

# Load model
pipe = StableDiffusionInpaintPipeline.from_pretrained(
    MODEL_ID,
    torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32
)
pipe = pipe.to(DEVICE)

# Load input image
image_path = "AG15_input_image.jpg"
image = Image.open(image_path).convert("RGB")
width, height = image.size

# Create micro edit region (1–2% of image area)
area = width * height
target_area = int(area * random.uniform(0.01, 0.02))

side = int(np.sqrt(target_area))

x = random.randint(0, width - side)
y = random.randint(0, height - side)

mask = np.zeros((height, width), dtype=np.uint8)
mask[y:y+side, x:x+side] = 255
mask_image = Image.fromarray(mask)

# Generate edited image
result = pipe(
    prompt=PROMPT,
    image=image,
    mask_image=mask_image,
    strength=0.6,
    guidance_scale=7.5,
).images[0]

# Save output
result.save("AG15_image_anomalyinjection_output.png")

print("Anomaly image saved: AG15_image_anomalyinjection_output.png")
print(f"Edit region: x={x}, y={y}, size={side}px")

 

Go (Golang) Script for AG #15

(as referenced in Section IIIC. Experimentation)

Prospective Efficacy Value-added Proposition: Front-loaded scene lock.



package main

import (
    "fmt"
    "image"
    "image/color"
    "image/png"
    "math"
    "math/rand"
    "os"
    "time"
)

func main() {

    rand.Seed(time.Now().UnixNano())

    datasetSize := 100

    for i := 0; i < datasetSize; i++ {

        generateSample(i)

    }

}

func generateSample(index int) {

    file,_ := os.Open("AG15_input_image.jpg")
    img,_,_ := image.Decode(file)

    bounds := img.Bounds()
    width := bounds.Dx()
    height := bounds.Dy()

    out := image.NewRGBA(bounds)

    // copy original image
    for y:=0; y<height; y++ {
        for x:=0; x<width; x++ {
            out.Set(x,y,img.At(x,y))
        }
    }

    // compute micro edit size
    totalPixels := width*height
    regionPixels := int(float64(totalPixels)*0.015)
    side := int(math.Sqrt(float64(regionPixels)))

    xStart := rand.Intn(width-side)
    yStart := rand.Intn(height-side)

    // apply subtle anomaly
    for y:=yStart; y<yStart+side; y++ {

        for x:=xStart; x<xStart+side; x++ {

            r,g,b,a := out.At(x,y).RGBA()

            r2 := clamp(int(r>>8) + rand.Intn(10) - 5)
            g2 := clamp(int(g>>8) + rand.Intn(10) - 5)
            b2 := clamp(int(b>>8) + rand.Intn(10) - 5)

            out.Set(x,y,color.RGBA{
                uint8(r2),
                uint8(g2),
                uint8(b2),
                uint8(a>>8),
            })
        }
    }

    // save image
    imgName := fmt.Sprintf("dataset/AG15_image_anomalyinjection_output_%03d.png",index)
    outFile,_ := os.Create(imgName)
    png.Encode(outFile,out)

    // write YOLO annotation
    labelName := fmt.Sprintf("dataset/AG15_image_anomalyinjection_output_%03d.txt",index)
    labelFile,_ := os.Create(labelName)

    xCenter := float64(xStart+side/2)/float64(width)
    yCenter := float64(yStart+side/2)/float64(height)

    boxW := float64(side)/float64(width)
    boxH := float64(side)/float64(height)

    fmt.Fprintf(labelFile,"0 %f %f %f %f",
        xCenter,yCenter,boxW,boxH)

}

func clamp(v int) int{

    if v<0 { return 0 }
    if v>255 { return 255 }

    return v
}

 

Rust Script for AG #15

(as referenced in Section IIIC. Experimentation)

Prospective Efficacy Value-added Proposition: Front-loaded scene lock.



use image::{GenericImageView};
use rand::Rng;

fn main() {

    // Load image
    let img = image::open("AG15_input_image.jpg").expect("Failed to open image");
    let (width, height) = img.dimensions();
    let mut img_buffer = img.to_rgb8();

    // Compute region size (1–2% of total image area)
    let total_pixels = width * height;
    let mut rng = rand::thread_rng();

    let region_pixels =
        (total_pixels as f32 * rng.gen_range(0.01..0.02)) as u32;

    let side = (region_pixels as f32).sqrt() as u32;

    // Random location
    let x = rng.gen_range(0..(width - side));
    let y = rng.gen_range(0..(height - side));

    // Apply subtle anomaly (minor color variation)
    for i in x..(x + side) {
        for j in y..(y + side) {

            let pixel = img_buffer.get_pixel_mut(i, j);

            let r = pixel[0] as i16 + rng.gen_range(-6..6);
            let g = pixel[1] as i16 + rng.gen_range(-6..6);
            let b = pixel[2] as i16 + rng.gen_range(-6..6);

            pixel[0] = r.clamp(0,255) as u8;
            pixel[1] = g.clamp(0,255) as u8;
            pixel[2] = b.clamp(0,255) as u8;
        }
    }

    // Save edited image
    img_buffer.save("AG15_image_anomalyinjection_output.png")
        .expect("Failed to save image");

    println!("Output saved: AG15_image_anomalyinjection_output.png");
    println!("Edit region: x={}, y={}, size={}px", x, y, side);
}

 

   In brief, the Python script is useful for prototyping (but slower) while Go (Golang) has high-throughput advantages and Rust can be ultra-high performance (and is well suited for bulk processing).