"""Produce original image-augmentation outputs and verify pixel transforms."""
from hashlib import sha256
from tempfile import TemporaryDirectory
import json
import platform
from pathlib import Path
import numpy as np
import tensorflow as tf
from tensorflow import keras
def emit(cases):
print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,keras=keras.__version__,
system=platform.system(),devices=[d.name for d in tf.config.list_physical_devices()],cases=cases)))
def observed(cases,name,operation,inputs,expected,actual,measurement=None):
assert expected==actual,(name,expected,actual)
row=dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True)
if measurement is not None:
row["measurements"]=measurement
cases.append(row)
class ColorShift(keras.layers.Layer):
def call(self,images,training=False):
if not training:
return images
return tf.clip_by_value(tf.image.adjust_saturation(tf.image.adjust_contrast(images,1.2),1.3),0,1)
def base_image(size):
row=tf.reshape(tf.linspace(0.,1.,size),(1,size))
col=tf.transpose(row)
x=tf.broadcast_to(row,(size,size))
y=tf.broadcast_to(col,(size,size))
mask=(x>.13)&(x<.4)&(y>.28)&(y<.7)
band=(y>.64)&(x>.46)&(x<.87)
return tf.stack((tf.where(mask,.86,x*.34+.05),tf.where(band,.77,y*.52+.18),
tf.where(mask,.21,(1-x)*.59+.15)),axis=-1)
def main():
cases=[]
keras.utils.set_random_seed(47)
image=base_image(128)
encoded=tf.image.convert_image_dtype(image,tf.uint8,saturate=True)
jpeg=tf.io.encode_jpeg(encoded,quality=95)
decoded=tf.io.decode_jpeg(jpeg,channels=3)
observed(cases,"jpeg_round_trip","encode owned RGB bytes and decode to the same layout",
{"quality":95},[[128,128,3],"uint8",True],
[list(decoded.shape),decoded.dtype.name,float(tf.reduce_mean(tf.abs(tf.cast(decoded,tf.float32)-tf.cast(encoded,tf.float32))))<6])
endpoints=tf.constant([[[0,128,255]]],tf.uint8)
unit=tf.cast(endpoints,tf.float32)/255
imagenet=(unit-tf.constant([.485,.456,.406]))/tf.constant([.229,.224,.225])
symmetric=2*unit-1
observed(cases,"three_normalizations","inspect endpoints and middle point for three normalization conventions",
[0,128,255],[[0.,.501961,1.],[-1.,.003922,1.],True],
[np.round(unit.numpy().reshape(-1).astype(float),6).tolist(),
np.round(symmetric.numpy().reshape(-1).astype(float),6).tolist(),float(imagenet[0,0,2])>2])
color=ColorShift()
vivid=color(image,training=True)
neutral=color(image,training=False)
bright=tf.image.adjust_brightness(image,.1)
observed(cases,"color_operations","change brightness, contrast and saturation and check neutral inference",
{"range":[0,1]},[True,True,True],[bool(np.array_equal(neutral,image)),
bool(np.any(np.abs(vivid-image)>1e-3)),abs(float(bright[0,0,0]-image[0,0,0])-.1)<1e-6])
patch=tf.image.crop_to_bounding_box(image,16,24,64,80)
padded=tf.image.resize_with_crop_or_pad(patch,80,100)
layer=keras.layers.RandomRotation((-15/360,15/360),seed=3)
spun=layer(image,training=True)
observed(cases,"crop_pad_and_rotate","crop without resampling, pad, and rotate via a Keras layer",
{"crop":[64,80],"rotation_degrees":15},[[64,80,3],[80,100,3],[128,128,3],True],
[list(patch.shape),list(padded.shape),list(spun.shape),bool(np.any(np.abs(spun-image)>1e-3))])
boxes=tf.constant([[[.1,.2,.7,.8]]])
mixed=.25*tf.zeros((1,8,8,3))+.75*tf.ones((1,8,8,3))
marked=tf.image.draw_bounding_boxes(mixed,boxes,tf.constant([[1.,0.,0.]]))
observed(cases,"blend_and_draw_boxes","combine two images and overlay a visible box",
{"blend_weights":[.25,.75]},[.75,[1,8,8,3],True],
[float(mixed[0,0,0,0]),list(marked.shape),bool(np.any(marked!=mixed))])
texture=tf.reshape(tf.range(4,dtype=tf.float32),(2,2,1))
stats=tf.image.per_image_standardization(texture)
observed(cases,"image_statistics","measure local variation and standardized image moments",
[0,1,2,3],[6.,0.,1.],[float(tf.image.total_variation(texture)),
round(float(tf.reduce_mean(stats)),6),round(float(tf.math.reduce_std(stats)),6)])
preprocess=keras.Sequential([keras.layers.RandomFlip("horizontal",seed=23),
keras.layers.RandomRotation(15/360,seed=42),keras.layers.RandomZoom(.1,seed=12),
keras.layers.Rescaling(1/255.)])
variants=preprocess(tf.repeat(tf.cast(encoded,tf.float32)[None,...],10,axis=0),training=True)
variants=tf.stack([color(x,training=True) for x in variants])
stable=preprocess(encoded[None,...],training=False)
observed(cases,"keras_preprocess_training_modes","keep rescaling at inference while disabling random geometry",
{"input":"uint8","count":10},[True,[10,128,128,3]],
[bool(np.allclose(stable,tf.cast(encoded[None,...],tf.float32)/255)),list(variants.shape)])
page=tf.concat([tf.concat(list(variants[:5]),axis=1),tf.concat(list(variants[5:]),axis=1)],axis=0)
output=Path(__file__).resolve().parent/"outputs/augmentations.png"
output.parent.mkdir(exist_ok=True)
blob=tf.io.encode_png(tf.image.convert_image_dtype(page,tf.uint8,saturate=True)).numpy()
output.write_bytes(blob)
observed(cases,"montage_observation","save the ten computed variants as a two-row PNG",
{"rows":2,"columns":5},[[256,640,3],True],
[list(tf.io.decode_png(blob).shape),bool(np.any(np.abs(variants[0]-variants[1])>1e-3))])
cases[-1]["artifact"]=dict(path="outputs/augmentations.png",sha256=sha256(blob).hexdigest(),bytes=len(blob))
options=tf.data.Options()
options.threading.private_threadpool_size=2
with TemporaryDirectory(prefix="mbsky-image-records-") as directory:
path=Path(directory)/"local.tfr"
raw=tf.io.encode_jpeg(tf.image.convert_image_dtype(base_image(264),tf.uint8,saturate=True)).numpy()
with tf.io.TFRecordWriter(str(path)) as stream:
for i in range(32):
feat={"image":tf.train.Feature(bytes_list=tf.train.BytesList(value=[raw])),
"label":tf.train.Feature(int64_list=tf.train.Int64List(value=[i%2]))}
stream.write(tf.train.Example(features=tf.train.Features(feature=feat)).SerializeToString())
def parse(i,record):
fields=tf.io.parse_single_example(record,{"image":tf.io.FixedLenFeature([],tf.string),
"label":tf.io.FixedLenFeature([],tf.int64)})
picture=tf.io.decode_jpeg(fields["image"],channels=3)
seed=tf.stack([5,tf.cast(i,tf.int32)])
picture=tf.image.stateless_random_crop(picture,[256,256,3],seed)
picture=tf.image.stateless_random_flip_left_right(picture,seed+1)
return tf.cast(picture,tf.float32)/127.5-1,fields["label"]
stream=tf.data.TFRecordDataset([str(path)]).enumerate().map(parse,num_parallel_calls=tf.data.AUTOTUNE)
batch=list(stream.batch(32).prefetch(tf.data.AUTOTUNE).with_options(options))
inputs,labels=batch[0]
observed(cases,"tfrecord_batch","parse labeled JPEG records, crop, flip and scale to a signed float range",
{"records":32,"crop":256},[1,[32,256,256,3],[0,1,0,1],True],
[len(batch),list(inputs.shape),labels[:4].numpy().tolist(),bool(tf.reduce_min(inputs)>=-1 and tf.reduce_max(inputs)<=1)])
windows=tf.image.extract_patches(image[None,...],[1,32,32,1],[1,32,32,1],[1,1,1,1],"VALID")
observed(cases,"extract_patches_layout","split a tensor into a four-by-four grid of flattened patches",
{"window":32},[1,4,4,3072],list(windows.shape))
emit(cases)
if __name__=="__main__":
main()
本例需在 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
入口文件:projects/tensorflow-image-data-processing-lab/transform-image-batches.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
transform-image-batches.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a367.zip