### Initialize Matplotlib and Load Image Source: https://github.com/nvlabs/ocrodeg/blob/master/README.md Sets up the plotting environment and loads a test image for degradation. Ensure 'testdata/W1P0.png' exists. ```python %pylab inline rc("image", cmap="gray", interpolation="bicubic") figsize(10, 10) import scipy.ndimage as ndi import ocrodeg image = imread("testdata/W1P0.png") imshow(image) ``` -------------------------------- ### Configure Plotting and Import Libraries Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Sets up image display properties (colormap and interpolation) and figure size for plotting. It also imports the scipy.ndimage module for image processing and the ocrodeg library. ```python rc("image", cmap="gray", interpolation="bicubic") figsize(10, 10) import scipy.ndimage as ndi import warnings warnings.filterwarnings("always") import ocrodeg ``` -------------------------------- ### Set Image Display Properties and Load Image Source: https://github.com/nvlabs/ocrodeg/blob/master/README.ipynb Configures image display properties such as colormap and interpolation, sets the figure size, and loads a sample image for processing. ```python rc("image", cmap="gray", interpolation="bicubic") figsize(10, 10) import scipy.ndimage as ndi import ocrodeg image = imread("testdata/W1P0.png") imshow(image) ``` -------------------------------- ### Load and Display Image Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Loads an image from a file and displays it. Requires the 'imread' and 'imshow' functions. ```python image = imread("testdata/W1P0.png") imshow(image) ``` -------------------------------- ### Generate Random Transformation Parameters Source: https://github.com/nvlabs/ocrodeg/blob/master/README.md Generates a dictionary of random parameters for geometric transformations. These parameters can be used to apply realistic degradations to document images. ```python ocrodeg.random_transform() ``` -------------------------------- ### Apply Gaussian Filter and Threshold to Patch Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies Gaussian filter and then a binary threshold to an image patch. Displays the resulting image. ```python for i, s in enumerate([0, 1, 2, 4]): subplot(2, 2, i+1) blurred = ndi.gaussian_filter(patch, s) thresholded = 1.0*(blurred>0.5) imshow(thresholded) ``` -------------------------------- ### Reload Ocrodeg and Generate Samples Source: https://github.com/nvlabs/ocrodeg/blob/master/README.ipynb Reloads the ocrodeg library and prepares to generate four samples, likely involving transformations or degradations. ```python reload(ocrodeg) for i in range(4): ``` -------------------------------- ### Generate a Single Random Fiber Path with Ocrodeg Source: https://context7.com/nvlabs/ocrodeg/llms.txt Simulates a single fiber path using a random walk with Cauchy-distributed angular steps. Returns an array of (x, y) coordinates representing the path. ```python import ocrodeg fiber = ocrodeg.make_fiber(l=300, a=0.2, stepsize=0.5) print(fiber.shape) # (300, 2) — 300 steps, (cos_acc, sin_acc) print(fiber[:5]) ``` -------------------------------- ### Generate Multiscale Noise with Ocrodeg Source: https://github.com/nvlabs/ocrodeg/blob/master/README.md Generates and displays four instances of multiscale uniform noise. Ensure 'ocrodeg' is imported and reloaded. ```python reload(ocrodeg) for i in range(4): noisy = ocrodeg.make_multiscale_noise_uniform((512, 512)) subplot(2, 2, i+1); imshow(noisy, vmin=0, vmax=1) ``` -------------------------------- ### Apply Fibrous Print-like Degradation with Ocrodeg Source: https://context7.com/nvlabs/ocrodeg/llms.txt Applies a fibrous paper background texture to create a more realistic aged-paper or newsprint appearance. Similar to `printlike_multiscale` but with enhanced fibrous texture. ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 patch = image[1900:2156, 1000:1256] # Fibrous paper simulation degraded_fibrous = ocrodeg.printlike_fibrous(patch) # Aged newsprint: more blur, more blotches aged = ocrodeg.printlike_fibrous(patch, blur=2.5, blotches=3e-4) print(degraded_fibrous.shape) # same as patch ``` -------------------------------- ### Apply Random Blotches to Image with Ocrodeg Source: https://context7.com/nvlabs/ocrodeg/llms.txt Overlays random foreground and background blotches on an image. Use `fgblobs` to add dark spots and `bgblobs` to remove ink. Adjust `fgscale` and `bgscale` for more intense effects. ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 patch = image[1900:2156, 1000:1256] # Light degradation: sparse blotches blotched = ocrodeg.random_blotches(patch, fgblobs=3e-4, bgblobs=1e-4) # Heavy degradation: many blotches heavily_blotched = ocrodeg.random_blotches( patch, fgblobs=1e-3, bgblobs=5e-4, fgscale=15, bgscale=8 ) assert blotched.shape == patch.shape assert blotched.dtype == np.dtype('f') ``` -------------------------------- ### random_blobs Source: https://context7.com/nvlabs/ocrodeg/llms.txt Creates a binary mask with irregularly shaped blobs, simulating dust, stains, or print artifacts. Parameters control density, size, and edge smoothness. ```APIDOC ## random_blobs(shape, blobdensity, size, roughness) ### Description Creates a binary mask with irregularly shaped blobs — useful for simulating dust, stains, or print artifacts on document images. `blobdensity` controls blobs per pixel; `size` controls blob radius; `roughness` controls edge smoothness. ### Parameters - **shape** (tuple) - The desired shape of the mask (e.g., (height, width)). - **blobdensity** (float) - The density of blobs per pixel. - **size** (float) - The approximate radius of the blobs. - **roughness** (float, optional) - Controls the smoothness of the blob edges. Defaults to 1.0. ### Returns - A numpy array representing the binary mask with random blobs. ``` -------------------------------- ### Generate Fibrous Paper Texture with Ocrodeg Source: https://context7.com/nvlabs/ocrodeg/llms.txt Renders a synthetic paper texture by drawing multiple random fiber paths and applying Gaussian blur. Models the appearance of fibrous paper stock. ```python import ocrodeg # Standard fibrous paper background fibrous = ocrodeg.make_fibrous_image( shape=(256, 256), nfibers=700, l=300, a=0.01, stepsize=0.5, limits=(0.1, 1.0), blur=1.0 ) print(fibrous.shape) # (256, 256) print(fibrous.min(), fibrous.max()) # 0.1, 1.0 ``` -------------------------------- ### Apply Multiscale Transformation Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies the `printlike_multiscale` transformation to an image patch and displays the original and transformed images side-by-side. Requires matplotlib for plotting. ```python subplot(121); imshow(patch); subplot(122); imshow(ocrodeg.printlike_multiscale(patch)) ``` -------------------------------- ### Apply affine transformation with ocrodeg.transform_image Source: https://context7.com/nvlabs/ocrodeg/llms.txt Applies affine transformations (rotation, scale, translation) to an image. Works with parameters from `random_transform()`. ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 # Apply a single known transform rotated = ocrodeg.transform_image(image, angle=1.5 * np.pi / 180, scale=0.95) # Apply a random transform (typical augmentation loop) for _ in range(4): params = ocrodeg.random_transform() augmented = ocrodeg.transform_image(image, **params) # augmented.shape == image.shape, dtype float32 # Anisotropic stretch (models scanning distortion) stretched = ocrodeg.transform_image(image, aniso=1.5) ``` -------------------------------- ### Apply Binary Blur with Noise to Patch Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies a binary blur operation with varying noise levels to an image patch using ocrodeg.binary_blur. Displays the resulting image. ```python for i, s in enumerate([0.0, 0.1, 0.2, 0.3]): subplot(2, 2, i+1) blurred = ocrodeg.binary_blur(patch, 2.0, noise=s) imshow(blurred) ``` -------------------------------- ### Measure Ink Coverage Percentage Source: https://context7.com/nvlabs/ocrodeg/llms.txt Returns the percentage of pixels with a value below 0.5, representing black or ink pixels. Useful for diagnostics and verifying ink mass preservation. ```python import ocrodeg import numpy as np image = np.zeros((100, 100), dtype='f') image[40:60, 40:60] = 1.0 # 20x20 white square on black background pct = ocrodeg.percent_black(image) print(pct) # 96.0 (96% of pixels are black/ink) ``` -------------------------------- ### Apply Gaussian Filter to Patch Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies Gaussian filter with different sigma values to an image patch. Displays the blurred patch. ```python for i, s in enumerate([0, 1, 2, 4]): subplot(2, 2, i+1) blurred = ndi.gaussian_filter(patch, s) imshow(blurred) ``` -------------------------------- ### Apply Multiscale Print-like Degradation with Ocrodeg Source: https://context7.com/nvlabs/ocrodeg/llms.txt Composites a clean binary document image over synthetic paper and ink textures with random blotches and Gaussian blur. Produces a realistic scanned-document appearance. ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 patch = image[1900:2156, 1000:1256] # Default: light blotches, sigma=1.0 blur degraded = ocrodeg.printlike_multiscale(patch) # Heavier degradation degraded_heavy = ocrodeg.printlike_multiscale(patch, blur=2.0, blotches=2e-4) print(degraded.shape) # same as patch print(degraded.min(), degraded.max()) # values in [0, 1] ``` -------------------------------- ### printlike_fibrous Source: https://context7.com/nvlabs/ocrodeg/llms.txt Applies a full fibrous print-like degradation pipeline, using a fibrous paper background for a more realistic aged appearance. ```APIDOC ## printlike_fibrous(image, blur, blotches) ### Description Similar to `printlike_multiscale`, but uses a fibrous paper background for a more realistic aged-paper or newsprint appearance. Composites the image over synthetic fibrous paper texture, with random blotches and Gaussian blur. ### Parameters - **image** (numpy.ndarray) - The input clean document image. - **blur** (float, optional) - The amount of Gaussian blur to apply. - **blotches** (float, optional) - Controls the density of random blotches. ### Request Example ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 patch = image[1900:2156, 1000:1256] # Fibrous paper simulation degraded_fibrous = ocrodeg.printlike_fibrous(patch) # Aged newsprint simulation aged = ocrodeg.printlike_fibrous(patch, blur=2.5, blotches=3e-4) print(degraded_fibrous.shape) ``` ### Response - **numpy.ndarray** - The degraded document image with a fibrous paper background. ``` -------------------------------- ### Compose Noise at Multiple Scales Source: https://context7.com/nvlabs/ocrodeg/llms.txt Combines noise from multiple spatial scales with optional weights, normalizing the result to specified limits. Models realistic paper texture with both fine and coarse grain. ```python import ocrodeg # Paper texture: dominant fine grain with some large-scale variation paper_texture = ocrodeg.make_multiscale_noise( shape=(512, 512), scales=[1.0, 5.0, 10.0, 50.0], weights=[1.0, 0.3, 0.5, 0.3], limits=(0.7, 1.0) # bright paper ) print(paper_texture.shape) # (512, 512) print(paper_texture.min(), paper_texture.max()) # 0.7, 1.0 ``` -------------------------------- ### Generate Random Blotches with Ocrodeg Source: https://github.com/nvlabs/ocrodeg/blob/master/README.md Applies random blotches to an image and displays the original and modified images side-by-side. The 'patch' variable is assumed to be defined. ```python reload(ocrodeg) blotched = ocrodeg.random_blotches(patch, 3e-4, 1e-4) #blotched = minimum(maximum(patch, ocrodeg.random_blobs(patch.shape, 30, 10)), 1-ocrodeg.random_blobs(patch.shape, 15, 8)) subplot(121); imshow(patch); subplot(122); imshow(blotched) ``` -------------------------------- ### Apply Binary Blur to Patch Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies a binary blur operation to an image patch using ocrodeg.binary_blur with different kernel sizes. Displays the blurred patch. ```python for i, s in enumerate([0.0, 1.0, 2.0, 4.0]): subplot(2, 2, i+1) blurred = ocrodeg.binary_blur(patch, s) imshow(blurred) ``` -------------------------------- ### printlike_multiscale Source: https://context7.com/nvlabs/ocrodeg/llms.txt Applies a full multiscale print-like degradation pipeline to a document image. ```APIDOC ## printlike_multiscale(image, blur, blotches) ### Description Composites a clean binary document image over synthetic paper and ink textures, with random blotches and Gaussian blur, to produce a realistic scanned-document appearance. ### Parameters - **image** (numpy.ndarray) - The input clean document image. - **blur** (float, optional) - The amount of Gaussian blur to apply. Defaults to 1.0. - **blotches** (float, optional) - Controls the density of random blotches. Defaults to a small value. ### Request Example ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 patch = image[1900:2156, 1000:1256] # Default degradation degraded = ocrodeg.printlike_multiscale(patch) # Heavier degradation degraded_heavy = ocrodeg.printlike_multiscale(patch, blur=2.0, blotches=2e-4) print(degraded.shape) print(degraded.min(), degraded.max()) ``` ### Response - **numpy.ndarray** - The degraded document image. ``` -------------------------------- ### Generate Random Binary Blob Mask Source: https://context7.com/nvlabs/ocrodeg/llms.txt Creates a binary mask with irregularly shaped blobs, useful for simulating dust, stains, or print artifacts. Adjust blobdensity, size, and roughness for different effects. ```python import ocrodeg # Sparse small blobs (dust particles) dust = ocrodeg.random_blobs((256, 256), blobdensity=3e-4, size=2) # Dense large blobs (paper stains) stains = ocrodeg.random_blobs((256, 256), blobdensity=1e-4, size=20, roughness=1.5) print(dust.dtype, dust.min(), dust.max()) # float32, 0.0, 1.0 print(stains.sum() / stains.size) # fraction of stained area ``` -------------------------------- ### make_fiber Source: https://context7.com/nvlabs/ocrodeg/llms.txt Generates a single random fiber path using a random walk with Cauchy-distributed angular steps. ```APIDOC ## make_fiber(l, a, stepsize) ### Description Simulates a single fiber (paper filament) as a random walk. Returns an array of (x, y) coordinates representing the fiber path. ### Parameters - **l** (int) - The number of steps in the fiber path. - **a** (float) - Controls the angular distribution of steps. - **stepsize** (float) - The step size for the random walk. ### Request Example ```python import ocrodeg fiber = ocrodeg.make_fiber(l=300, a=0.2, stepsize=0.5) print(fiber.shape) print(fiber[:5]) ``` ### Response - **numpy.ndarray** - An array of shape (l, 2) containing (x, y) coordinates of the fiber path. ``` -------------------------------- ### Extract and Display Image Patch Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Extracts a specific patch from an image and displays it. Requires 'imshow'. ```python patch = image[1900:2156, 1000:1256] imshow(patch) ``` -------------------------------- ### transform_image(image, angle, scale, aniso, translation, order) Source: https://context7.com/nvlabs/ocrodeg/llms.txt Applies an affine transformation to a document image using rotation, uniform scaling, anisotropic scaling, and translation. Works seamlessly with the output of `random_transform()`. Uses `scipy.ndimage.affine_transform` with nearest-neighbor boundary handling. ```APIDOC ## transform_image(image, angle, scale, aniso, translation, order) ### Description Applies an affine transformation to a document image using rotation, uniform scaling, anisotropic scaling, and translation. Works seamlessly with the output of `random_transform()`. Uses `scipy.ndimage.affine_transform` with nearest-neighbor boundary handling. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **image** (numpy.ndarray) - The input image as a NumPy array. - **angle** (float, optional) - Rotation angle in radians. Defaults to 0. - **scale** (float, optional) - Uniform scaling factor. Defaults to 1.0. - **aniso** (float, optional) - Anisotropic scaling factor. Defaults to 1.0. - **translation** (tuple, optional) - Translation offsets (tx, ty). Defaults to (0, 0). - **order** (int, optional) - The order of the spline interpolation. Defaults to 1 (bilinear). ### Request Example ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 # Apply a single known transform rotated = ocrodeg.transform_image(image, angle=1.5 * np.pi / 180, scale=0.95) # Apply a random transform (typical augmentation loop) for _ in range(4): params = ocrodeg.random_transform() augmented = ocrodeg.transform_image(image, **params) # augmented.shape == image.shape, dtype float32 # Anisotropic stretch (models scanning distortion) stretched = ocrodeg.transform_image(image, aniso=1.5) ``` ### Response #### Success Response (200) - **augmented_image** (numpy.ndarray) - The transformed image. #### Response Example ```json { "example": "Transformed image data" } ``` ``` -------------------------------- ### Apply Fibrous Transformation Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies the `printlike_fibrous` transformation to an image patch and displays the original and transformed images side-by-side. Requires matplotlib for plotting. ```python subplot(121); imshow(patch); subplot(122); imshow(ocrodeg.printlike_fibrous(patch)) ``` -------------------------------- ### autoinvert(image) Source: https://context7.com/nvlabs/ocrodeg/llms.txt Ensures the image is in ink-on-white (dark foreground) orientation by checking pixel distribution and inverting if the image is predominantly dark (white-on-black). Input must be a float array with values in [0, 1]. ```APIDOC ## autoinvert(image) ### Description Ensures the image is in ink-on-white (dark foreground) orientation by checking pixel distribution and inverting if the image is predominantly dark (white-on-black). Input must be a float array with values in `[0, 1]`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import numpy as np import ocrodeg # Simulate a white-on-black image (inverted polarity) image = np.ones((256, 256), dtype='f') * 0.9 image[100:150, 80:180] = 0.1 # dark background, light text corrected = ocrodeg.autoinvert(image) # corrected is now in ink-on-white orientation (values flipped) print(corrected.min(), corrected.max()) # 0.1, 0.9 ``` ### Response #### Success Response (200) - **corrected** (numpy.ndarray) - The image with corrected polarity. #### Response Example ```json { "example": "0.1, 0.9" } ``` ``` -------------------------------- ### random_transform(...) Source: https://context7.com/nvlabs/ocrodeg/llms.txt Generates a dictionary of randomly sampled transformation parameters suitable for document image augmentation: rotation angle (radians), scale factor, anisotropic scaling, and translation offsets. All parameter ranges can be overridden via keyword arguments. ```APIDOC ## random_transform(...) ### Description Generates a dictionary of randomly sampled transformation parameters suitable for document image augmentation: rotation angle (radians), scale factor, anisotropic scaling, and translation offsets. All parameter ranges can be overridden via keyword arguments. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import ocrodeg # Default ranges: translation ±5%, rotation ±2°, scale ±10%, aniso ±10% params = ocrodeg.random_transform() print(params) # {'angle': -0.016, 'aniso': 0.805, 'scale': 0.971, 'translation': (0.014, 0.037)} # Custom ranges for stronger augmentation params_strong = ocrodeg.random_transform( translation=(-0.1, 0.1), rotation=(-5, 5), scale=(-0.2, 0.2), aniso=(-0.2, 0.2) ) print(params_strong) ``` ### Response #### Success Response (200) - **params** (dict) - A dictionary containing random transformation parameters: 'angle', 'aniso', 'scale', 'translation'. #### Response Example ```json { "example": "{'angle': -0.016, 'aniso': 0.805, 'scale': 0.971, 'translation': (0.014, 0.037)}" } ``` ``` -------------------------------- ### Load IPython and Matplotlib Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Loads the necessary libraries for interactive plotting within an IPython environment. This is typically used in Jupyter notebooks. ```python %pylab inline ``` -------------------------------- ### random_blotches Source: https://context7.com/nvlabs/ocrodeg/llms.txt Overlays random foreground blobs (dark spots) and background blobs (white patches) on a document image. ```APIDOC ## random_blotches(image, fgblobs, bgblobs, fgscale, bgscale) ### Description Applies random foreground and background ink blotches to an image. `fgblobs` adds dark spots, while `bgblobs` removes ink, creating white patches. ### Parameters - **image** (numpy.ndarray) - The input image. - **fgblobs** (float) - Controls the density of foreground blotches (dark spots). - **bgblobs** (float) - Controls the density of background blotches (white patches). - **fgscale** (int, optional) - Scaling factor for foreground blotches. - **bgscale** (int, optional) - Scaling factor for background blotches. ### Request Example ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 patch = image[1900:2156, 1000:1256] # Light degradation blotched = ocrodeg.random_blotches(patch, fgblobs=3e-4, bgblobs=1e-4) # Heavy degradation heavily_blotched = ocrodeg.random_blotches( patch, fgblobs=1e-3, bgblobs=5e-4, fgscale=15, bgscale=8 ) ``` ### Response - **numpy.ndarray** - The image with applied blotches. ``` -------------------------------- ### Generate Fibrous Image Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Generates a fibrous image using ocrodeg.make_fibrous_image with specified dimensions and parameters. Displays the generated image. ```python imshow(ocrodeg.make_fibrous_image((256, 256), 700, 300, 0.01)) ``` -------------------------------- ### Transform Image with Scale (Cropped) Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies image transformation with different scale factors and displays a cropped portion of the transformed image centered around the image's middle. ```python for i, scale in enumerate([0.5, 0.9, 1.0, 2.0]): subplot(2, 2, i+1) h, w = image.shape imshow(ocrodeg.transform_image(image, scale=scale)[h//2-200:h//2+200, w//3-200:w//3+200]) ``` -------------------------------- ### Generate Random Blotches on Patch Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies random blotches to an image patch using ocrodeg.random_blotches. Displays the original and blotched images side-by-side. ```python blotched = ocrodeg.random_blotches(patch, 3e-4, 1e-4) #blotched = minimum(maximum(patch, ocrodeg.random_blobs(patch.shape, 30, 10)), 1-ocrodeg.random_blobs(patch.shape, 15, 8)) subplot(121); imshow(patch); subplot(122); imshow(blotched) ``` -------------------------------- ### Apply Binary Blur Source: https://github.com/nvlabs/ocrodeg/blob/master/README.md Applies a binary blur effect to an image patch using `ocrodeg.binary_blur`. The `s` parameter controls the blur radius. ```python reload(ocrodeg) for i, s in enumerate([0.0, 1.0, 2.0, 4.0]): subplot(2, 2, i+1) blurred = ocrodeg.binary_blur(patch, s) imshow(blurred) ``` -------------------------------- ### make_fibrous_image Source: https://context7.com/nvlabs/ocrodeg/llms.txt Generates a synthetic paper texture by drawing random fiber paths and applying Gaussian blur. ```APIDOC ## make_fibrous_image(shape, nfibers, l, a, stepsize, limits, blur) ### Description Renders a synthetic paper texture by drawing multiple random fiber paths onto a canvas and applying Gaussian blur. Models the appearance of fibrous paper stock. ### Parameters - **shape** (tuple) - The desired shape (height, width) of the output image. - **nfibers** (int) - The number of fibers to draw. - **l** (int) - The length of each fiber path. - **a** (float) - Controls the angular distribution of fiber steps. - **stepsize** (float) - The step size for the fiber random walk. - **limits** (tuple) - A tuple (min, max) for the intensity limits of the paper texture. - **blur** (float) - The amount of Gaussian blur to apply. ### Request Example ```python import ocrodeg fibrous = ocrodeg.make_fibrous_image( shape=(256, 256), nfibers=700, l=300, a=0.01, stepsize=0.5, limits=(0.1, 1.0), blur=1.0 ) print(fibrous.shape) print(fibrous.min(), fibrous.max()) ``` ### Response - **numpy.ndarray** - A NumPy array representing the fibrous paper texture. ``` -------------------------------- ### Auto-invert image polarity with ocrodeg.autoinvert Source: https://context7.com/nvlabs/ocrodeg/llms.txt Ensures image polarity is ink-on-white. Input must be a float array with values in [0, 1]. ```python import numpy as np import ocrodeg # Simulate a white-on-black image (inverted polarity) image = np.ones((256, 256), dtype='f') * 0.9 image[100:150, 80:180] = 0.1 # dark background, light text corrected = ocrodeg.autoinvert(image) # corrected is now in ink-on-white orientation (values flipped) print(corrected.min(), corrected.max()) # 0.1, 0.9 ``` -------------------------------- ### Transform Image with Anisotropy (Cropped) Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies image transformation with varying anisotropy values and displays a cropped portion of the transformed image. ```python for i, aniso in enumerate([0.5, 1.0, 1.5, 2.0]): subplot(2, 2, i+1) imshow(ocrodeg.transform_image(image, aniso=aniso)[1000:1500, 750:1250]) ``` -------------------------------- ### Generate Multiscale Noise Image Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Generates a multiscale noise image using ocrodeg.make_multiscale_noise_uniform. Displays the generated noise image. ```python for i in range(4): noisy = ocrodeg.make_multiscale_noise_uniform((512, 512)) subplot(2, 2, i+1); imshow(noisy, vmin=0, vmax=1) ``` -------------------------------- ### bounded_gaussian_noise(shape, sigma, maxdelta) Source: https://context7.com/nvlabs/ocrodeg/llms.txt Generates a 2-channel displacement field of shape `(2, H, W)` using Gaussian-smoothed random noise, clipped to a maximum displacement of `maxdelta` pixels. Used as input to `distort_with_noise` for elastic warping. ```APIDOC ## bounded_gaussian_noise(shape, sigma, maxdelta) ### Description Generates a 2-channel displacement field of shape `(2, H, W)` using Gaussian-smoothed random noise, clipped to a maximum displacement of `maxdelta` pixels. Used as input to `distort_with_noise` for elastic warping. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import ocrodeg shape = (1024, 1024) # sigma=2.0: fine-grained ink-spread simulation; sigma=20.0: paper warp noise_fine = ocrodeg.bounded_gaussian_noise(shape, sigma=2.0, maxdelta=2.0) noise_coarse = ocrodeg.bounded_gaussian_noise(shape, sigma=20.0, maxdelta=10.0) print(noise_fine.shape) # (2, 1024, 1024) print(noise_fine.min(), noise_fine.max()) # approx -2.0, 2.0 ``` ### Response #### Success Response (200) - **displacement_field** (numpy.ndarray) - A 2-channel NumPy array representing the displacement field. #### Response Example ```json { "example": "(2, 1024, 1024)" } ``` ``` -------------------------------- ### Transform Image with Rotation (Cropped) Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies image transformation with specified rotation angles and displays a cropped portion of the transformed image. ```python for i, angle in enumerate([-2, -1, 0, 1]): subplot(2, 2, i+1) imshow(ocrodeg.transform_image(image, angle=angle*pi/180)[1000:1500, 750:1250]) ``` -------------------------------- ### Apply Random Geometric Transformations Source: https://github.com/nvlabs/ocrodeg/blob/master/README.md Applies a set of random geometric transformations to an image. Each transformation uses parameters generated by `ocrodeg.random_transform()`. ```python for i in xrange(4): subplot(2, 2, i+1) imshow(ocrodeg.transform_image(image, **ocrodeg.random_transform())) ``` -------------------------------- ### make_multiscale_noise Source: https://context7.com/nvlabs/ocrodeg/llms.txt Composes noise from multiple spatial scales with optional weights and normalizes the result to specified limits. Models realistic paper texture. ```APIDOC ## make_multiscale_noise(shape, scales, weights, limits) ### Description Combines noise generated at multiple spatial scales with optional per-scale weights. Normalizes the result to the specified `limits` range. Models realistic paper texture with both fine and coarse grain. ### Parameters - **shape** (tuple) - The desired shape of the noise array (e.g., (height, width)). - **scales** (list of float) - A list of spatial scales for noise generation. - **weights** (list of float) - A list of weights corresponding to each scale. - **limits** (tuple) - A tuple (min, max) specifying the desired output range. ### Returns - A numpy array representing the composed multiscale noise. ``` -------------------------------- ### Generate Random Blobs on Patch Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Generates random blobs on an image patch using ocrodeg.random_blobs with varying parameters. Displays the resulting image. ```python for i, s in enumerate([2, 5, 10, 20]): subplot(2, 2, i+1) imshow(ocrodeg.random_blobs(patch.shape, 3e-4, s)) ``` -------------------------------- ### Generate 1D Ruled-Surface Distortion (Paper Curl) Source: https://context7.com/nvlabs/ocrodeg/llms.txt Creates a displacement field for 1D distortion, modeling paper curl. The displacement is a smoothed 1D noise signal broadcast across all rows. Use for simulating paper curl effects. ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 # Mild curl noise_mild = ocrodeg.noise_distort1d(image.shape, sigma=100.0, magnitude=5.0) curled_mild = ocrodeg.distort_with_noise(image, noise_mild) # Strong curl (book spine effect) noise_strong = ocrodeg.noise_distort1d(image.shape, sigma=100.0, magnitude=200.0) curled_strong = ocrodeg.distort_with_noise(image, noise_strong) print(noise_mild.shape) # (2, H, W) — only dy channel is non-zero ``` -------------------------------- ### Generate Random Multiscale Noise Source: https://context7.com/nvlabs/ocrodeg/llms.txt Creates random multiscale noise by selecting scales and weights randomly. Scales are log-uniformly sampled within a given range. Each call produces a different texture. ```python import ocrodeg # Four different random paper textures for i in range(4): texture = ocrodeg.make_multiscale_noise_uniform( shape=(512, 512), srange=(1.0, 100.0), nscales=4, limits=(0.0, 1.0) ) print(f"Sample {i}: min={texture.min():.3f}, max={texture.max():.3f}") ``` -------------------------------- ### Distort Image with Gaussian Noise Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies Gaussian noise to an image and then distorts it. Displays a cropped portion of the distorted image. ```python for i, sigma in enumerate([1.0, 2.0, 5.0, 20.0]): subplot(2, 2, i+1) noise = ocrodeg.bounded_gaussian_noise(image.shape, sigma, 5.0) distorted = ocrodeg.distort_with_noise(image, noise) h, w = image.shape imshow(distorted[h//2-200:h//2+200, w//3-200:w//3+200]) ``` -------------------------------- ### Generate Uniform Multiscale Noise Source: https://github.com/nvlabs/ocrodeg/blob/master/README.ipynb Generates a multiscale uniform noise image. Requires matplotlib for display. ```python noisy = ocrodeg.make_multiscale_noise_uniform((512, 512)) subplot(2, 2, i+1); imshow(noisy, vmin=0, vmax=1) ``` -------------------------------- ### Generate bounded Gaussian noise for distortion with ocrodeg.bounded_gaussian_noise Source: https://context7.com/nvlabs/ocrodeg/llms.txt Generates a 2-channel displacement field using Gaussian-smoothed noise, clipped to `maxdelta`. Used for elastic warping. ```python import ocrodeg shape = (1024, 1024) # sigma=2.0: fine-grained ink-spread simulation; sigma=20.0: paper warp noise_fine = ocrodeg.bounded_gaussian_noise(shape, sigma=2.0, maxdelta=2.0) noise_coarse = ocrodeg.bounded_gaussian_noise(shape, sigma=20.0, maxdelta=10.0) print(noise_fine.shape) # (2, 1024, 1024) print(noise_fine.min(), noise_fine.max()) # approx -2.0, 2.0 ``` -------------------------------- ### Generate random geometric transform parameters with ocrodeg.random_transform Source: https://context7.com/nvlabs/ocrodeg/llms.txt Returns random parameters for geometric augmentation: rotation, scale, anisotropic scaling, and translation. Default ranges can be overridden. ```python import ocrodeg # Default ranges: translation ±5%, rotation ±2°, scale ±10%, aniso ±10% params = ocrodeg.random_transform() print(params) # {'angle': -0.016, 'aniso': 0.805, 'scale': 0.971, 'translation': (0.014, 0.037)} # Custom ranges for stronger augmentation params_strong = ocrodeg.random_transform( translation=(-0.1, 0.1), rotation=(-5, 5), scale=(-0.2, 0.2), aniso=(-0.2, 0.2) ) print(params_strong) ``` -------------------------------- ### Generate Noise at a Single Spatial Scale Source: https://context7.com/nvlabs/ocrodeg/llms.txt Generates uniform random noise and upsamples it to a given spatial scale using zoom interpolation. This is a building block for composing multiscale noise. ```python import ocrodeg noise = ocrodeg.make_noise_at_scale((512, 512), scale=10.0) print(noise.shape) # (512, 512) print(noise.min(), noise.max()) # values in [0, 1] ``` -------------------------------- ### Mass-Preserving Binary Blur Source: https://context7.com/nvlabs/ocrodeg/llms.txt Blurs a binary document image while preserving ink mass. Optionally adds Gaussian noise before thresholding to simulate uneven ink density. Useful for modeling ink spread on paper. ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 patch = image[1900:2156, 1000:1256] # Simple blur — ink mass preserved blurred = ocrodeg.binary_blur(patch, sigma=2.0) # Blur with added noise — simulates uneven ink absorption noisy_blurred = ocrodeg.binary_blur(patch, sigma=2.0, noise=0.1) print(f"Original black%: {ocrodeg.percent_black(patch):.1f}%") print(f"Blurred black%: {ocrodeg.percent_black(blurred):.1f}%") # nearly identical ``` -------------------------------- ### make_noise_at_scale Source: https://context7.com/nvlabs/ocrodeg/llms.txt Generates uniform random noise upsampled to a specific spatial scale. This is a building block for creating multiscale noise compositions. ```APIDOC ## make_noise_at_scale(shape, scale) ### Description Generates uniform random noise upsampled to a given spatial scale using zoom interpolation. Building block for multiscale noise composition. ### Parameters - **shape** (tuple) - The desired shape of the noise array (e.g., (height, width)). - **scale** (float) - The spatial scale at which to generate the noise. ### Returns - A numpy array of the specified shape containing noise values between 0 and 1. ``` -------------------------------- ### make_multiscale_noise_uniform Source: https://context7.com/nvlabs/ocrodeg/llms.txt Generates random multiscale noise by randomly selecting scales and weights within a given range. Each call produces a different texture. ```APIDOC ## make_multiscale_noise_uniform(shape, srange, nscales, limits) ### Description Like `make_multiscale_noise` but randomly selects the scales and weights, making each call produce a different texture. Scales are log-uniformly sampled in `srange`. ### Parameters - **shape** (tuple) - The desired shape of the noise array (e.g., (height, width)). - **srange** (tuple) - A tuple (min_scale, max_scale) for log-uniform sampling of scales. - **nscales** (int) - The number of scales to use. - **limits** (tuple) - A tuple (min, max) specifying the desired output range. ### Returns - A numpy array representing the random multiscale noise. ``` -------------------------------- ### binary_blur Source: https://context7.com/nvlabs/ocrodeg/llms.txt Applies a mass-preserving binary blur to a document image, optionally adding Gaussian noise to simulate uneven ink density. Useful for modeling ink spread. ```APIDOC ## binary_blur(image, sigma, noise) ### Description Blurs a binary (or near-binary) document image while preserving the proportion of black pixels (ink mass). Optionally adds Gaussian noise before thresholding to simulate uneven ink density. Useful for modeling ink spread on paper. ### Parameters - **image** (numpy.ndarray) - The input image. - **sigma** (float) - The standard deviation for the Gaussian blur. - **noise** (float, optional) - The amount of Gaussian noise to add before thresholding. Defaults to 0. ### Returns - A numpy array representing the blurred image. ``` -------------------------------- ### Elastically warp image with displacement field using ocrodeg.distort_with_noise Source: https://context7.com/nvlabs/ocrodeg/llms.txt Applies elastic distortion to an image using a displacement field. Uses `scipy.ndimage.map_coordinates`. ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 h, w = image.shape # Simulate light ink spread (small sigma, small maxdelta) noise = ocrodeg.bounded_gaussian_noise(image.shape, sigma=1.0, maxdelta=2.0) distorted_subtle = ocrodeg.distort_with_noise(image, noise) # Simulate strong page warp noise_warp = ocrodeg.bounded_gaussian_noise(image.shape, sigma=10.0, maxdelta=20.0) distorted_warped = ocrodeg.distort_with_noise(image, noise_warp) assert distorted_subtle.shape == image.shape ``` -------------------------------- ### Distort Image with 1D Noise Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies 1D noise to an image and then distorts it. Displays the top portion of the distorted image. ```python for i, mag in enumerate([5.0, 20.0, 100.0, 200.0]): subplot(2, 2, i+1) noise = ocrodeg.noise_distort1d(image.shape, magnitude=mag) distorted = ocrodeg.distort_with_noise(image, noise) h, w = image.shape imshow(distorted[:1500]) ``` -------------------------------- ### distort_with_noise(image, deltas, order) Source: https://context7.com/nvlabs/ocrodeg/llms.txt Applies a 2D elastic distortion to an image using a precomputed displacement field `deltas` of shape `(2, H, W)`. Uses `scipy.ndimage.map_coordinates` with reflection boundary mode. ```APIDOC ## distort_with_noise(image, deltas, order) ### Description Applies a 2D elastic distortion to an image using a precomputed displacement field `deltas` of shape `(2, H, W)`. Uses `scipy.ndimage.map_coordinates` with reflection boundary mode. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **image** (numpy.ndarray) - The input image as a NumPy array. - **deltas** (numpy.ndarray) - A 2-channel displacement field of shape `(2, H, W)`. - **order** (int, optional) - The order of the spline interpolation. Defaults to 1 (bilinear). ### Request Example ```python import numpy as np import scipy.ndimage as ndi import ocrodeg image = np.array(ndi.imread("testdata/W1P0.png"), dtype='f') / 255.0 h, w = image.shape # Simulate light ink spread (small sigma, small maxdelta) noise = ocrodeg.bounded_gaussian_noise(image.shape, sigma=1.0, maxdelta=2.0) distorted_subtle = ocrodeg.distort_with_noise(image, noise) # Simulate strong page warp noise_warp = ocrodeg.bounded_gaussian_noise(image.shape, sigma=10.0, maxdelta=20.0) distorted_warped = ocrodeg.distort_with_noise(image, noise_warp) assert distorted_subtle.shape == image.shape ``` ### Response #### Success Response (200) - **distorted_image** (numpy.ndarray) - The elastically distorted image. #### Response Example ```json { "example": "Distorted image data" } ``` ``` -------------------------------- ### Transform Image with Scale Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies image transformation with different scale factors. Displays the transformed image in subplots. ```python for i, scale in enumerate([0.5, 0.9, 1.0, 2.0]): subplot(2, 2, i+1) imshow(ocrodeg.transform_image(image, scale=scale)) ``` -------------------------------- ### Transform Image with Anisotropy Source: https://github.com/nvlabs/ocrodeg/blob/master/test-degrade.ipynb Applies image transformation with varying anisotropy values. Displays the transformed image in subplots. ```python for i, aniso in enumerate([0.5, 1.0, 1.5, 2.0]): subplot(2, 2, i+1) imshow(ocrodeg.transform_image(image, aniso=aniso)) ```