images

package module
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: BSD-3-Clause Imports: 17 Imported by: 8 modules, 7 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-images/images

images — go-images

Docs License Go Status

A pure-Go (no cgo) image-processing library in the style of scikit-image, built on the Go standard library's image, image/color, image/png and image/jpeg packages, with decoding of six further container formats (GIF, WebP, TIFF, BMP, ICO, ICNS) delegated to the shared reference registry go-gfx/gfx/codec — still entirely CGO-free.

Every operation is a pure function: it takes an image and returns a freshly allocated *image.RGBA, never mutating its input.

Why not just use a C library?

The established image stacks all need a native C dependency: ruby-vips wraps libvips, RMagick wraps ImageMagick, and the cgo-backed Go wrappers pull in the same shared libraries. That makes cross-compilation and embedding awkward. go-images/images is CGO=0: it builds and runs identically on every Go target with no system packages, which makes it trivially cross-compilable and embeddable (for example inside go-embedded-ruby).

Pure-Go image libraries already exist (bild, disintegration/imaging); the goal here is a clean, correct, fully test-covered core whose hot pixel kernels run SIMD inner loops from go-simd/floats (the shared axpy kernel: AVX2 FMA on amd64, NEON on arm64, portable elsewhere) plus multicore tiling, across the six supported 64-bit targets (amd64, arm64, riscv64, loong64, ppc64le, s390x). See docs/plan-images.md for the roadmap and an honest comparison.

API

import "github.com/go-images/images"     // operations + file I/O (links every decoder)
import "github.com/go-images/images/ops" // operations only, no codec
Only processing pixels? Import ops

Every pixel operation below lives in the codec-free subpackage ops; package images forwards each one under the same name and adds the I/O. The split exists for the linker: each decoder registers itself with image.RegisterFormat in an init function, and the Go linker keeps whatever a reachable init reaches, so importing images links JPEG 2000, JBIG2, TIFF, WebP, BMP, ICO, GIF, PNG and JPEG decoders even in a program that never reads a file. Measured on a GOOS=js GOARCH=wasm program that draws one go-widgets label: those decoders were about 1.7 MB of its 7 MB of code. A program that only resizes, blurs or transforms should import ops (ops.GaussianBlur, ops.Resize, …); TestOpsLinksNoCodec keeps it that way.

Conversion and I/O:

  • images.ToRGBA(img image.Image) *image.RGBA

  • images.Load(path string) (*image.RGBA, error)

  • images.Save(path string, img image.Image) error — format by extension (.png, .jpg, .jpeg)

  • images.Decode(r io.Reader) (*image.RGBA, error) — format auto-detected (PNG, JPEG, GIF, WebP, TIFF, BMP, ICO, ICNS)

  • images.DecodeBest(r io.Reader, targetSize int) (*image.RGBA, error) — like Decode, but picks the representation nearest targetSize for multi-image containers (ICO, ICNS)

  • images.Encode(w io.Writer, img image.Image, format images.Format) error — images.PNG, images.JPEG

  • images.DecodePartial(r io.Reader) (*image.RGBA, int, error) — an image that may still be arriving: the picture at full size and how many rows of it are real

  • images.DecodePartialFile(path string) (*image.RGBA, int, error) — the same, on a file being written

  • images.DecodeWith(r io.Reader, opt images.DecodeOptions) (*image.RGBA, error) and images.DecodePartialWith(r, opt) — Decode/DecodePartial with options: MaxPixels (the pixel ceiling) and TargetSize (as DecodeBest)

Size limit

An image file states its own size, and a compressed format states a large one in a few bytes: a 1×1 PNG whose header claims 16000×16000 made the standard decoder allocate about 1 GB (1 024 182 312 bytes measured) before reading a pixel. Every decode entry point (Decode, DecodeBest, DecodeWith, DecodePartial, Load, the Exif variants) therefore reads the header first and refuses an image above DecodeOptions.MaxPixels, default codec.DefaultMaxPixels = 40 000 000 (a 50-megapixel camera photo is above it). The error wraps codec.ErrTooLarge (errors.Is), for PNG and JPEG as well as for the formats decoded through go-gfx/gfx, and nothing has been allocated when it is returned.

// a photo library: raise the ceiling to what you actually accept
img, err := images.DecodeWith(r, images.DecodeOptions{MaxPixels: 120_000_000})
if errors.Is(err, codec.ErrTooLarge) { /* refuse politely */ }
Decoding a picture that is still arriving

Every standard decoder is all-or-nothing, which for a file still arriving is the same as having nothing. Measured on a real photograph truncated at three fractions, image/jpeg, image/png and image/gif each returned a nil image and an error every time, with three quarters of the picture on disk.

img, rows, err := images.DecodePartial(r)
// draw img's first `rows` rows; err says what stopped the decode

Rows past the count hold whatever the image was allocated with. The error comes back with the picture and is nil only when everything arrived, in which case the count is every row.

Three of the eight formats can answer, through forks of the standard decoders that keep what they decoded: png, jpeg, gif (its first frame). Each refuses some shapes of its own — an interlaced PNG or GIF, a progressive or CMYK JPEG — for reasons stated where the refusal is made.

The other five say so and name themselves. WebP is the one that could not be forked the same way: its frame is a VP8 keyframe, decoded as a whole rather than row by row, so there is no partial state to hand back.

One divergence worth knowing: on a complete file DecodePartial returns the fork's decode, and for a four-component JPEG that differs from Decode — the fork upsamples chroma the way libjpeg does. Decode's standard-library path is untouched.

Operations (each returns a new *image.RGBA):

Point & colour:

  • images.Grayscale(img) — luminance-weighted (Rec. 601)
  • images.Invert(img)
  • images.AdjustBrightness(img, delta) — clamped to [0, 255]
  • images.AdjustContrast(img, factor) — about mid-point 128, clamped
  • images.RGBToHSV(img) / images.HSVToRGB(img) — byte-encoded, round-trip-stable
  • images.OtsuThreshold(img) — Otsu level (matches skimage.filters.threshold_otsu)
  • images.OtsuThresholdGray(g) — the same level read in place from an *image.Gray, no RGBA copy
  • images.Threshold(img, t) / images.Otsu(img) — binarise on luminance

Filters:

  • images.Convolve(img, images.Kernel{...}) — arbitrary odd kernel, clamp-to-edge
  • images.GaussianBlur(img, sigma) — separable Gaussian
  • images.BoxBlur(img, radius) — separable running-sum mean (matches scipy.ndimage.uniform_filter)
  • images.Median(img, radius) — square median (matches scipy.ndimage.median_filter, mode="nearest")
  • images.UnsharpMask(img, radius, amount) — sharpen via src + amount*(src − blur) (matches skimage.filters.unsharp_mask)
  • images.Sharpen(img) — UnsharpMask(img, 1.0, 1.0)

Edges:

  • images.Sobel(img) — gradient-magnitude edge map (classic integer kernels, on luminance)
  • images.SobelX(img) / images.SobelY(img) — directional Sobel responses (mid-grey = zero gradient)
  • images.Prewitt(img) / images.Scharr(img) / images.SobelMag(img) — normalised gradient magnitude (match skimage.filters.{prewitt,scharr,sobel})
  • images.Laplacian(img) — discrete Laplacian (matches skimage.filters.laplace, ksize 3)
  • images.Canny(img, sigma, low, high) — binary Canny edge map (Gaussian → Sobel → bilinear NMS → hysteresis)

Morphology (grayscale square element, also binary on 0/255 images):

  • images.Erode(img, r) / images.Dilate(img, r) — local min / max
  • images.Open(img, r) / images.Close(img, r) — erode→dilate / dilate→erode

Geometry:

  • images.Resize(img, w, h, mode) — images.NearestNeighbor, images.Bilinear, images.Area, images.Bicubic or images.Lanczos. The resampling kernels live once, in the shared foundation go-gfx/gfx/resample; Resize delegates to them over a zero-copy raster view, so nothing is duplicated here.

    • Area is area/box averaging (PIL Image.BOX, OpenCV INTER_AREA; at integer ratios, scikit-image downscale_local_mean). The mode to reduce with — nearest keeps one source pixel in sixteen when shrinking by four, and bilinear never looks at more than four neighbours however far the image is shrunk.
    • Bicubic (Catmull-Rom) and Lanczos (a = 3) are Pillow's BICUBIC / LANCZOS: their footprint widens with the reduction factor, so they antialias a reduction and sharpen an enlargement. Their colour channels are filtered in premultiplied-alpha space, so a transparent pixel's colour never bleeds into the visible edge of a cut-out.

    NearestNeighbor, Bilinear and Area are proven byte-for-byte identical to the kernels this library previously carried (see resize_dedup_control_test.go).

  • images.FlipHorizontal(img) / images.FlipVertical(img) — numpy.fliplr / flipud

  • images.Rotate90(img) / images.Rotate180(img) / images.Rotate270(img) — numpy.rot90

  • images.Transpose(img) / images.Transverse(img) — reflections across the main and anti-diagonal (PIL Image.TRANSPOSE / Image.TRANSVERSE)

  • images.Crop(img, image.Rect(x0, y0, x1, y1))

  • images.ExifTranspose(img, orientation) and the auto-orienting decoders images.DecodeExifTranspose(r) / images.LoadExifTranspose(path) — apply the eight EXIF orientations so a photo displays the right way up, the geometry of Pillow's ImageOps.exif_transpose. The orientation tag is read from a JPEG's APP1/Exif segment (or a bare TIFF) with a minimal in-package reader; an absent or invalid tag is treated as "normal" and the image is returned unrotated.

  • images.Rotate(img, angleDegrees, resize) — arbitrary-angle rotation about the centre, bilinear, matching skimage.transform.rotate (byte-for-byte; resize=true grows the canvas to fit, sized exactly as scikit-image does)

  • images.SkewAngle(img, images.SkewOptions{}) — how far a scanned page is tilted, in degrees, in Rotate's own convention: a page produced by Rotate(img, a, …) measures a. Baird's method (The skew angle of printed documents, Proc. SPSE 1987): the page is sheared rather than rotated — which keeps the scan-line counts exact, where resampling would blur the very line structure being measured — and the angle taken is the one that maximises the variance of the marked-pixel count per scan line. Criterion: images.AdjacentDifference selects Postl's (1986) sum of squared differences between neighbouring profile elements instead; on a page of text the two agree to the search step. MaxPixels (2 000 000 by default) bounds the work, and is a bound on untrusted input rather than a speed knob: cost is pixels × angles. A page with nothing on it reports images.ErrSkewBlank rather than 0°, which would be indistinguishable from a page measured and found level.

  • images.Deskew(img, threshold, opt) — measure the tilt and put the page straight, returning the corrected image and the angle. A tilt below threshold degrees is reported and left alone, byte for byte: a page that is already level should not come back softened by a resample. Judged by tesseract, which knows nothing of this code: a page it reads at 0.968 similarity straight, and at 0.895 tilted by 7°, it reads back at 0.968 once deskewed.

  • images.ConnectedComponents(mask, opt) — label the foreground (non-zero pixels) of a *image.Gray and return each component's bounding box, area and seed pixel (its first pixel in reading order, so a caller can flood-fill exactly that component), 4- or 8-connected (8 by default, so a diagonal stroke is one stroke). Run-based union-find: memory follows the number of runs, not pixels. Checked against a plain flood fill on random masks and by a fuzz target. The input is untrusted: MaxPixels, MaxRuns (a checkerboard is the worst case) and MaxComponents are refused before the memory is allocated, with images.ErrComponentLimit.

  • ops.RotateGray(g, angle, fill) — Rotate's geometry and bilinear sampling on a *image.Gray, in one byte per pixel instead of eight (RGBA in, RGBA out), with the outside filled by fill. With fill 0 it is channel 0 of Rotate, byte for byte.

  • images.Warp(img, inv, outW, outH, interp, mode, cval) — general affine resampling, matching skimage.transform.warp (clip=False). inv is an images.Affine mapping output (col,row) to input (col,row) — the inverse of the transform being applied, exactly as scikit-image's warp takes an inverse map. interp is InterpNearest (order 0) or InterpBilinear (order 1); mode is BorderConstant (fill with cval) or BorderEdge. Build transforms with images.Identity/Translation/Scaling/Rotation and compose them with .Then(...); invert with .Invert().

Example
src, err := images.Load("in.png")
if err != nil {
    log.Fatal(err)
}
gray := images.Grayscale(src)
blurred, err := images.GaussianBlur(gray, 2.0)
if err != nil {
    log.Fatal(err)
}
if err := images.Save("out.png", blurred); err != nil {
    log.Fatal(err)
}

Performance

A rigorous parity benchmark against scikit-image 0.26 / scipy 1.18 and OpenCV 4.13 lives in BENCHMARKS.md (reproducible harness in benchmarks/). Headline, single-thread, core-for-core on an Apple M4 Max:

  • Wins vs scikit-image: box blur 1.8–2.6× (O(1) running-window sum), RGB→HSV ~4.8× (fused pass), flip ~2×, Gaussian 1.0–1.3× (the former Gaussian loss is now closed by the SIMD axpy separable convolution), and Sobel 1.02–1.06× (the former recompute-per-pixel loss is now closed by a cached luminance plane and a branch-free interior run).
  • Morphology — now at scikit-image parity. The O(radius) fold was replaced with the O(1) van Herk / Gil-Werman running min/max, so erode/dilate are flat in radius and reach parity → 1.02× of scikit-image at 4096² single-thread (≈0.8× at small radius is a pure constant factor → SIMD).
  • Gaps vs scikit-image: the residual single-thread gap (small-radius morphology, and Rotate90/Crop/Otsu against a bare numpy view/copy or histogram, which is not comparable per-pixel work) is now a pure constant factor; closing it with go-asmgen SIMD across all six arches is BENCHMARKS.md action item C.
  • Multicore: with all cores go-images is faster than single-threaded scikit-image on every op (morphology now 4.8–7.8×, Sobel now 4.2–4.8×), but OpenCV's O(1)+SIMD morphology is still far ahead — cores don't replace SIMD.

Box blur and grayscale morphology match SciPy bit-for-bit; Gaussian within one LSB; every SIMD kernel is validated against its scalar oracle. See BENCHMARKS.md for the full tables, methodology and action items, and docs/perf.md for the historical SIMD notes.

License

BSD-3-Clause. See LICENSE.

Documentation

Overview

Package images is a pure-Go (cgo-free) image-processing library in the style of scikit-image, built on the Go standard library's image, image/color, image/png and image/jpeg packages.

Unlike the established options in the Ruby world — ruby-vips (libvips) and RMagick (ImageMagick) — and unlike cgo-backed Go wrappers, this library has no native C dependency: it is CGO=0 and builds and runs identically on every Go target. That makes it trivially cross-compilable and embeddable (for example inside go-embedded-ruby), at the cost — for now — of the hand-tuned SIMD that libvips/ImageMagick rely on. A later phase will close that gap with SIMD kernels generated by go-asmgen across the six supported 64-bit targets. See docs/plan-images.md for the roadmap and an honest comparison with the existing pure-Go libraries (bild, disintegration/imaging).

Operations are pure functions: each takes an image and returns a freshly allocated *image.RGBA, never mutating its input. Use ToRGBA to convert an arbitrary image.Image to the *image.RGBA the operations consume, and the I/O helpers (Load, Save, Decode, Encode). Decode auto-detects eight container formats — PNG and JPEG via the standard library, and GIF, WebP, TIFF, BMP, ICO and ICNS via the shared reference registry github.com/go-gfx/gfx/codec; Encode writes PNG and JPEG.

Phase 0 implements Grayscale, Invert, Resize (nearest-neighbour, bilinear, area/box, and the high-quality bicubic and Lanczos modes, all delegated to the shared go-gfx/gfx/resample foundation), Convolve (arbitrary odd-sized kernels with edge clamping), GaussianBlur (separable), AdjustBrightness and AdjustContrast.

Phase 1 adds edge detection — Sobel (gradient magnitude) with SobelX/SobelY directional responses, the normalised Prewitt, Scharr and SobelMag operators and the Laplacian (matching skimage.filters.{prewitt,scharr,sobel,laplace}), and the full Canny detector (Gaussian, Sobel, bilinear non-maximum suppression, hysteresis); the filters BoxBlur (separable running-sum mean, matching scipy.ndimage.uniform_filter), Median (square median, matching scipy.ndimage.median_filter), and UnsharpMask/Sharpen (matching skimage.filters.unsharp_mask); the geometric transforms FlipHorizontal, FlipVertical, Rotate90/Rotate180/Rotate270 (numpy.fliplr/flipud/rot90) and Crop; the colour conversions RGBToHSV/HSVToRGB; and thresholding via OtsuThreshold/Threshold/Otsu (matching skimage.filters.threshold_otsu).

Phase 2 adds grayscale morphology over a square structuring element: Erode and Dilate (per-channel local min/max, matching scipy.ndimage.grey_erosion and grey_dilation) and the derived Open and Close. On binary 0/255 images these reduce to ordinary binary morphology.

The operations are implemented in the codec-free subpackage github.com/go-images/images/ops and forwarded here under the same names. A program that only processes pixels should import ops: importing this package links every decoder above, because each registers itself in an init function and the linker keeps what an init reaches.

docs/perf.md reports honest go-images-vs-scikit-image/SciPy benchmarks and correctness checks for the hot operations.

Index

Constants

View Source
const (
	AdjacentDifference = ops.AdjacentDifference
	Area               = ops.Area
	Bicubic            = ops.Bicubic
	Bilinear           = ops.Bilinear
	BorderConstant     = ops.BorderConstant
	BorderEdge         = ops.BorderEdge

	DefaultComponentMaxComponents = ops.DefaultComponentMaxComponents
	DefaultComponentMaxPixels     = ops.DefaultComponentMaxPixels
	DefaultComponentMaxRuns       = ops.DefaultComponentMaxRuns

	InterpBilinear  = ops.InterpBilinear
	InterpNearest   = ops.InterpNearest
	Lanczos         = ops.Lanczos
	NearestNeighbor = ops.NearestNeighbor
	Variance        = ops.Variance
)

The constants of ops, under their names here.

Variables

View Source
var (
	ErrComponentLimit   = ops.ErrComponentLimit
	ErrComponentOptions = ops.ErrComponentOptions
	ErrSkewAtLimit      = ops.ErrSkewAtLimit
	ErrSkewBlank        = ops.ErrSkewBlank
	ErrSkewEmpty        = ops.ErrSkewEmpty
	ErrSkewOptions      = ops.ErrSkewOptions
)

The errors of ops, under their names here.

Functions

func AdjustBrightness

func AdjustBrightness(img image.Image, delta float64) *image.RGBA

AdjustBrightness forwards to ops.AdjustBrightness, the codec-free implementation.

func AdjustBrightnessRaster

func AdjustBrightnessRaster(src *raster.Image, delta float64) *raster.Image

AdjustBrightnessRaster forwards to ops.AdjustBrightnessRaster, the codec-free implementation.

func AdjustContrast

func AdjustContrast(img image.Image, factor float64) *image.RGBA

AdjustContrast forwards to ops.AdjustContrast, the codec-free implementation.

func AdjustContrastRaster

func AdjustContrastRaster(src *raster.Image, factor float64) *raster.Image

AdjustContrastRaster forwards to ops.AdjustContrastRaster, the codec-free implementation.

func AsRGBA

func AsRGBA(r *raster.Image) *image.RGBA

AsRGBA forwards to ops.AsRGBA, the codec-free implementation.

func AsRaster

func AsRaster(img *image.RGBA) *raster.Image

AsRaster forwards to ops.AsRaster, the codec-free implementation.

func BoxBlur

func BoxBlur(img image.Image, radius int) (*image.RGBA, error)

BoxBlur forwards to ops.BoxBlur, the codec-free implementation.

func BoxBlurRaster

func BoxBlurRaster(src *raster.Image, radius int) (*raster.Image, error)

BoxBlurRaster forwards to ops.BoxBlurRaster, the codec-free implementation.

func Canny

func Canny(img image.Image, sigma, low, high float64) (*image.RGBA, error)

Canny forwards to ops.Canny, the codec-free implementation.

func CannyRaster

func CannyRaster(src *raster.Image, sigma, low, high float64) (*raster.Image, error)

CannyRaster forwards to ops.CannyRaster, the codec-free implementation.

func Close

func Close(img image.Image, radius int) (*image.RGBA, error)

Close forwards to ops.Close, the codec-free implementation.

func CloseRaster

func CloseRaster(src *raster.Image, radius int) (*raster.Image, error)

CloseRaster forwards to ops.CloseRaster, the codec-free implementation.

func Convolve

func Convolve(img image.Image, k Kernel) (*image.RGBA, error)

Convolve forwards to ops.Convolve, the codec-free implementation.

func ConvolveRaster

func ConvolveRaster(src *raster.Image, k Kernel) (*raster.Image, error)

ConvolveRaster forwards to ops.ConvolveRaster, the codec-free implementation.

func Crop

func Crop(img image.Image, r image.Rectangle) (*image.RGBA, error)

Crop forwards to ops.Crop, the codec-free implementation.

func CropRaster

func CropRaster(src *raster.Image, r image.Rectangle) (*raster.Image, error)

CropRaster forwards to ops.CropRaster, the codec-free implementation.

func Decode

func Decode(r io.Reader) (*image.RGBA, error)

Decode reads an image from r, auto-detecting the container format from its magic bytes, and returns it converted to *image.RGBA.

Eight formats are recognised. PNG and JPEG are decoded by the standard library exactly as before — this path is byte-for-byte unchanged. The six additional formats (GIF, WebP, TIFF, BMP, ICO, ICNS) are delegated to the shared reference registry github.com/go-gfx/gfx/codec, which reimplements no decoder and hands each container to a battle-tested pure-Go (CGO-free) library. For the multi-representation containers (ICO, ICNS) the largest representation is returned; use DecodeBest to target a pixel size.

Alpha convention: every source is brought into this package under the same premultiplied-at-input convention that ToRGBA already applies to any non-*image.RGBA source. codec returns straight (non-premultiplied) alpha, so its output is routed back through ToRGBA to premultiply, keeping the whole library's decoded bytes consistent regardless of container format.

func DecodeBest

func DecodeBest(r io.Reader, targetSize int) (*image.RGBA, error)

DecodeBest is Decode with a target pixel size for the multi-representation containers (ICO, ICNS): among their stored representations it selects the one whose longer side is the smallest that is still at least targetSize, falling back to the largest when none reaches it. A targetSize <= 0 selects the largest, making it identical to Decode. targetSize is ignored for single-image formats. The result is a premultiplied *image.RGBA, exactly as from Decode.

func DecodeExifTranspose

func DecodeExifTranspose(r io.Reader) (*image.RGBA, error)

DecodeExifTranspose decodes an image from r and returns it already re-oriented according to its embedded EXIF orientation tag, as a premultiplied *image.RGBA. It is the auto-orienting counterpart of Decode: an image with no EXIF orientation (or a non-JPEG/TIFF source) is returned unrotated. This is the equivalent of Pillow's ImageOps.exif_transpose applied at decode time.

func DecodePartial

func DecodePartial(r io.Reader) (*image.RGBA, int, error)

DecodePartial reads an image from r that may still be arriving, and returns what of it is real: the picture at its full declared size, and the number of pixel rows that are COMPLETE counting from the top. Rows past the count hold whatever the image was allocated with, so a caller draws the first rows and nothing else.

The error that stopped the decode comes back with them, and is nil only when the whole image arrived — in which case the count is every row.

⛔ Every standard decoder is all-or-nothing, which for a file still arriving is the same as having nothing. Measured on a real photograph truncated at three fractions, image/jpeg, image/png and image/gif each returned a nil image and an error EVERY time, with three quarters of the picture on disk. This is why the three forks behind this call exist.

Three of the eight formats Decode recognises can answer, and each refuses some shapes of its own — an interlaced PNG or GIF, a progressive or CMYK JPEG — for reasons written where the refusal is made:

  • PNG, by github.com/go-images/png
  • JPEG, by github.com/go-images/jpeg
  • GIF, by github.com/go-images/gif (its first frame)

The other five (WebP, TIFF, BMP, ICO, ICNS) report that they cannot. WebP is the one that could not simply be forked the same way: its frame is a VP8 keyframe, decoded as a whole rather than row by row, so there is no partial state to hand back.

⛔ One divergence from Decode, stated rather than hidden. On a COMPLETE file this returns the FORK's decode, and for a four-component JPEG that differs: the fork upsamples chroma the way libjpeg does, where the standard library repeats each sample. See github.com/go-images/jpeg. Decode's standard-library path is untouched, so anything relying on its exact bytes still gets them.

func DecodePartialFile

func DecodePartialFile(path string) (*image.RGBA, int, error)

DecodePartialFile is DecodePartial on a path, for the common case of watching a file grow on disk.

func DecodePartialWith added in v0.3.0

func DecodePartialWith(r io.Reader, opt DecodeOptions) (*image.RGBA, int, error)

DecodePartialWith is DecodePartial with options; only opt.MaxPixels applies. An image whose header declares more pixels is refused with an error wrapping codec.ErrTooLarge — the forks allocate the full declared raster up front.

func DecodeWith added in v0.3.0

func DecodeWith(r io.Reader, opt DecodeOptions) (*image.RGBA, error)

DecodeWith is Decode with options. An image above opt.MaxPixels is refused with an error wrapping codec.ErrTooLarge (errors.Is sees it) for every format, PNG and JPEG included; Decode and DecodeBest apply the default.

func Deskew added in v0.2.0

func Deskew(img image.Image, threshold float64, opt SkewOptions) (*image.RGBA, float64, error)

Deskew forwards to ops.Deskew, the codec-free implementation.

func Dilate

func Dilate(img image.Image, radius int) (*image.RGBA, error)

Dilate forwards to ops.Dilate, the codec-free implementation.

func DilateRaster

func DilateRaster(src *raster.Image, radius int) (*raster.Image, error)

DilateRaster forwards to ops.DilateRaster, the codec-free implementation.

func Encode

func Encode(w io.Writer, img image.Image, format Format) error

Encode writes img to w in the given format.

func Erode

func Erode(img image.Image, radius int) (*image.RGBA, error)

Erode forwards to ops.Erode, the codec-free implementation.

func ErodeRaster

func ErodeRaster(src *raster.Image, radius int) (*raster.Image, error)

ErodeRaster forwards to ops.ErodeRaster, the codec-free implementation.

func ExifTranspose

func ExifTranspose(img image.Image, o Orientation) *image.RGBA

ExifTranspose returns a copy of img re-oriented so that it displays the right way up, applying the geometric transform that the EXIF orientation o calls for. It mirrors Pillow's ImageOps.exif_transpose geometry:

1 identity          2 flip horizontal    3 rotate 180     4 flip vertical
5 transpose         6 rotate 90 CW       7 transverse     8 rotate 90 CCW

Orientations 5-8 swap the width and height. Any value outside 1-8 (including a zero Orientation) is treated as OrientationNormal and returns an unrotated RGBA copy, matching Pillow's lenient handling of an absent or invalid tag.

func FlipHorizontal

func FlipHorizontal(img image.Image) *image.RGBA

FlipHorizontal forwards to ops.FlipHorizontal, the codec-free implementation.

func FlipHorizontalRaster

func FlipHorizontalRaster(src *raster.Image) *raster.Image

FlipHorizontalRaster forwards to ops.FlipHorizontalRaster, the codec-free implementation.

func FlipVertical

func FlipVertical(img image.Image) *image.RGBA

FlipVertical forwards to ops.FlipVertical, the codec-free implementation.

func FlipVerticalRaster

func FlipVerticalRaster(src *raster.Image) *raster.Image

FlipVerticalRaster forwards to ops.FlipVerticalRaster, the codec-free implementation.

func GaussianBlur

func GaussianBlur(img image.Image, sigma float64) (*image.RGBA, error)

GaussianBlur forwards to ops.GaussianBlur, the codec-free implementation.

func GaussianBlurRaster

func GaussianBlurRaster(src *raster.Image, sigma float64) (*raster.Image, error)

GaussianBlurRaster forwards to ops.GaussianBlurRaster, the codec-free implementation.

func Grayscale

func Grayscale(img image.Image) *image.RGBA

Grayscale forwards to ops.Grayscale, the codec-free implementation.

func GrayscaleRaster

func GrayscaleRaster(src *raster.Image) *raster.Image

GrayscaleRaster forwards to ops.GrayscaleRaster, the codec-free implementation.

func HSVToRGB

func HSVToRGB(img image.Image) *image.RGBA

HSVToRGB forwards to ops.HSVToRGB, the codec-free implementation.

func HSVToRGBRaster

func HSVToRGBRaster(src *raster.Image) *raster.Image

HSVToRGBRaster forwards to ops.HSVToRGBRaster, the codec-free implementation.

func Invert

func Invert(img image.Image) *image.RGBA

Invert forwards to ops.Invert, the codec-free implementation.

func InvertRaster

func InvertRaster(src *raster.Image) *raster.Image

InvertRaster forwards to ops.InvertRaster, the codec-free implementation.

func Laplacian

func Laplacian(img image.Image) *image.RGBA

Laplacian forwards to ops.Laplacian, the codec-free implementation.

func LaplacianRaster

func LaplacianRaster(src *raster.Image) *raster.Image

LaplacianRaster forwards to ops.LaplacianRaster, the codec-free implementation.

func Load

func Load(path string) (*image.RGBA, error)

Load reads and decodes the image at path, returning it as *image.RGBA. The format is auto-detected from the file contents.

func LoadExifTranspose

func LoadExifTranspose(path string) (*image.RGBA, error)

LoadExifTranspose reads the image at path and returns it re-oriented per its EXIF orientation tag, as a premultiplied *image.RGBA. It is the auto-orienting counterpart of Load.

func Median

func Median(img image.Image, radius int) (*image.RGBA, error)

Median forwards to ops.Median, the codec-free implementation.

func MedianRaster

func MedianRaster(src *raster.Image, radius int) (*raster.Image, error)

MedianRaster forwards to ops.MedianRaster, the codec-free implementation.

func Open

func Open(img image.Image, radius int) (*image.RGBA, error)

Open forwards to ops.Open, the codec-free implementation.

func OpenRaster

func OpenRaster(src *raster.Image, radius int) (*raster.Image, error)

OpenRaster forwards to ops.OpenRaster, the codec-free implementation.

func Otsu

func Otsu(img image.Image) *image.RGBA

Otsu forwards to ops.Otsu, the codec-free implementation.

func OtsuRaster

func OtsuRaster(src *raster.Image) *raster.Image

OtsuRaster forwards to ops.OtsuRaster, the codec-free implementation.

func OtsuThreshold

func OtsuThreshold(img image.Image) uint8

OtsuThreshold forwards to ops.OtsuThreshold, the codec-free implementation.

func OtsuThresholdGray added in v0.5.0

func OtsuThresholdGray(g *image.Gray) uint8

OtsuThresholdGray forwards to ops.OtsuThresholdGray, the codec-free implementation.

func Prewitt

func Prewitt(img image.Image) *image.RGBA

Prewitt forwards to ops.Prewitt, the codec-free implementation.

func PrewittRaster

func PrewittRaster(src *raster.Image) *raster.Image

PrewittRaster forwards to ops.PrewittRaster, the codec-free implementation.

func RGBToHSV

func RGBToHSV(img image.Image) *image.RGBA

RGBToHSV forwards to ops.RGBToHSV, the codec-free implementation.

func RGBToHSVRaster

func RGBToHSVRaster(src *raster.Image) *raster.Image

RGBToHSVRaster forwards to ops.RGBToHSVRaster, the codec-free implementation.

func Resize

func Resize(img image.Image, w, h int, mode ResizeMode) (*image.RGBA, error)

Resize forwards to ops.Resize, the codec-free implementation.

func ResizeRaster

func ResizeRaster(src *raster.Image, w, h int, mode ResizeMode) (*raster.Image, error)

ResizeRaster forwards to ops.ResizeRaster, the codec-free implementation.

func Rotate

func Rotate(img image.Image, angle float64, resize bool) *image.RGBA

Rotate forwards to ops.Rotate, the codec-free implementation.

func Rotate90

func Rotate90(img image.Image) *image.RGBA

Rotate90 forwards to ops.Rotate90, the codec-free implementation.

func Rotate90Raster

func Rotate90Raster(src *raster.Image) *raster.Image

Rotate90Raster forwards to ops.Rotate90Raster, the codec-free implementation.

func Rotate180

func Rotate180(img image.Image) *image.RGBA

Rotate180 forwards to ops.Rotate180, the codec-free implementation.

func Rotate180Raster

func Rotate180Raster(src *raster.Image) *raster.Image

Rotate180Raster forwards to ops.Rotate180Raster, the codec-free implementation.

func Rotate270

func Rotate270(img image.Image) *image.RGBA

Rotate270 forwards to ops.Rotate270, the codec-free implementation.

func Rotate270Raster

func Rotate270Raster(src *raster.Image) *raster.Image

Rotate270Raster forwards to ops.Rotate270Raster, the codec-free implementation.

func RotateGray added in v0.4.0

func RotateGray(src *image.Gray, angle float64, fill uint8) *image.Gray

RotateGray forwards to ops.RotateGray, the codec-free implementation.

func Save

func Save(path string, img image.Image) error

Save encodes img and writes it to path, choosing the format from the file extension: ".png" for PNG and ".jpg" or ".jpeg" for JPEG (case-insensitive). It returns an error for any other extension.

func Scharr

func Scharr(img image.Image) *image.RGBA

Scharr forwards to ops.Scharr, the codec-free implementation.

func ScharrRaster

func ScharrRaster(src *raster.Image) *raster.Image

ScharrRaster forwards to ops.ScharrRaster, the codec-free implementation.

func Sharpen

func Sharpen(img image.Image) *image.RGBA

Sharpen forwards to ops.Sharpen, the codec-free implementation.

func SharpenRaster

func SharpenRaster(src *raster.Image) *raster.Image

SharpenRaster forwards to ops.SharpenRaster, the codec-free implementation.

func SkewAngle added in v0.2.0

func SkewAngle(img image.Image, opt SkewOptions) (float64, error)

SkewAngle forwards to ops.SkewAngle, the codec-free implementation.

func Sobel

func Sobel(img image.Image) *image.RGBA

Sobel forwards to ops.Sobel, the codec-free implementation.

func SobelMag

func SobelMag(img image.Image) *image.RGBA

SobelMag forwards to ops.SobelMag, the codec-free implementation.

func SobelMagRaster

func SobelMagRaster(src *raster.Image) *raster.Image

SobelMagRaster forwards to ops.SobelMagRaster, the codec-free implementation.

func SobelRaster

func SobelRaster(src *raster.Image) *raster.Image

SobelRaster forwards to ops.SobelRaster, the codec-free implementation.

func SobelX

func SobelX(img image.Image) *image.RGBA

SobelX forwards to ops.SobelX, the codec-free implementation.

func SobelXRaster

func SobelXRaster(src *raster.Image) *raster.Image

SobelXRaster forwards to ops.SobelXRaster, the codec-free implementation.

func SobelY

func SobelY(img image.Image) *image.RGBA

SobelY forwards to ops.SobelY, the codec-free implementation.

func SobelYRaster

func SobelYRaster(src *raster.Image) *raster.Image

SobelYRaster forwards to ops.SobelYRaster, the codec-free implementation.

func Threshold

func Threshold(img image.Image, t uint8) *image.RGBA

Threshold forwards to ops.Threshold, the codec-free implementation.

func ThresholdRaster

func ThresholdRaster(src *raster.Image, t uint8) *raster.Image

ThresholdRaster forwards to ops.ThresholdRaster, the codec-free implementation.

func ToRGBA

func ToRGBA(img image.Image) *image.RGBA

ToRGBA forwards to ops.ToRGBA, the codec-free implementation.

func Transpose

func Transpose(img image.Image) *image.RGBA

Transpose forwards to ops.Transpose, the codec-free implementation.

func Transverse

func Transverse(img image.Image) *image.RGBA

Transverse forwards to ops.Transverse, the codec-free implementation.

func UnsharpMask

func UnsharpMask(img image.Image, radius, amount float64) (*image.RGBA, error)

UnsharpMask forwards to ops.UnsharpMask, the codec-free implementation.

func UnsharpMaskRaster

func UnsharpMaskRaster(src *raster.Image, radius, amount float64) (*raster.Image, error)

UnsharpMaskRaster forwards to ops.UnsharpMaskRaster, the codec-free implementation.

func Warp

func Warp(img image.Image, inv Affine, outW, outH int, interp Interp, mode BorderMode, cval float64) *image.RGBA

Warp forwards to ops.Warp, the codec-free implementation.

Types

type Affine

type Affine = ops.Affine

Affine is ops.Affine.

func Identity

func Identity() Affine

Identity forwards to ops.Identity, the codec-free implementation.

func Rotation

func Rotation(theta float64) Affine

Rotation forwards to ops.Rotation, the codec-free implementation.

func Scaling

func Scaling(sx, sy float64) Affine

Scaling forwards to ops.Scaling, the codec-free implementation.

func Translation

func Translation(tx, ty float64) Affine

Translation forwards to ops.Translation, the codec-free implementation.

type BorderMode

type BorderMode = ops.BorderMode

BorderMode is ops.BorderMode.

type Component added in v0.4.0

type Component = ops.Component

Component is ops.Component.

func ConnectedComponents added in v0.4.0

func ConnectedComponents(mask *image.Gray, opt ComponentOptions) ([]Component, error)

ConnectedComponents forwards to ops.ConnectedComponents, the codec-free implementation.

type ComponentOptions added in v0.4.0

type ComponentOptions = ops.ComponentOptions

ComponentOptions is ops.ComponentOptions.

type DecodeOptions added in v0.3.0

type DecodeOptions struct {
	// TargetSize selects among the representations of ICO and ICNS, as in
	// [DecodeBest]; <= 0 selects the largest. Ignored for single-image formats.
	TargetSize int

	// MaxPixels refuses an image whose header declares more pixels than this,
	// before anything is allocated for it. Zero (or negative) means
	// codec.DefaultMaxPixels, forty million pixels.
	//
	// ⛔ The number it guards comes from the FILE: a PNG declaring 16000x16000 is
	// a few dozen bytes and a gigabyte once decoded. A caller whose input is
	// legitimately larger (a 50-megapixel camera photo) raises it; a service
	// decoding files from strangers lowers it to what it actually needs.
	MaxPixels int
}

DecodeOptions tunes DecodeWith, and mirrors github.com/go-gfx/gfx/codec.Options.

type Format

type Format int

Format identifies an encodable image format.

const (
	// PNG is the lossless PNG format.
	PNG Format = iota
	// JPEG is the lossy JPEG format, encoded at the package's default quality.
	JPEG
)

type Interp

type Interp = ops.Interp

Interp is ops.Interp.

type Kernel

type Kernel = ops.Kernel

Kernel is ops.Kernel.

type Orientation

type Orientation uint8

Orientation is the EXIF image-orientation tag (TIFF tag 0x0112). Its eight legal values, 1 through 8, each describe how the stored pixels must be transformed to be displayed the right way up. ExifTranspose applies the matching transform. OrientationNormal (1) is the identity.

const (
	// OrientationNormal (1) needs no transform.
	OrientationNormal Orientation = 1
	// OrientationFlipHorizontal (2) is mirrored left-to-right.
	OrientationFlipHorizontal Orientation = 2
	// OrientationRotate180 (3) is rotated 180 degrees.
	OrientationRotate180 Orientation = 3
	// OrientationFlipVertical (4) is mirrored top-to-bottom.
	OrientationFlipVertical Orientation = 4
	// OrientationTranspose (5) is reflected across the main diagonal.
	OrientationTranspose Orientation = 5
	// OrientationRotate90CW (6) needs a 90-degree clockwise rotation.
	OrientationRotate90CW Orientation = 6
	// OrientationTransverse (7) is reflected across the anti-diagonal.
	OrientationTransverse Orientation = 7
	// OrientationRotate90CCW (8) needs a 90-degree counter-clockwise rotation.
	OrientationRotate90CCW Orientation = 8
)

The eight EXIF orientation values, named for the transform each one calls for. The comment on each is the geometric operation ExifTranspose applies.

func OrientationFromExif

func OrientationFromExif(data []byte) Orientation

OrientationFromExif extracts the EXIF orientation tag from an encoded image's bytes (a JPEG APP1/Exif segment, or a bare TIFF stream). It is deliberately lenient: when no EXIF block, no orientation tag, or a malformed structure is found, it returns OrientationNormal so callers can auto-orient unconditionally. A value stored outside the legal 1-8 range is also normalised to OrientationNormal.

type ResizeMode

type ResizeMode = ops.ResizeMode

ResizeMode is ops.ResizeMode.

type SkewCriterion added in v0.2.0

type SkewCriterion = ops.SkewCriterion

SkewCriterion is ops.SkewCriterion.

type SkewOptions added in v0.2.0

type SkewOptions = ops.SkewOptions

SkewOptions is ops.SkewOptions.

Directories

Path Synopsis
benchmarks module
internal
kernels
Package kernels holds the per-pixel inner loops used by the public image operations.
Package kernels holds the per-pixel inner loops used by the public image operations.
Package ops is the codec-free core of github.com/go-images/images: every pixel operation (resize, convolution, blurs, edges, morphology, colour, geometric transforms, warps, the raster facades) and nothing that decodes or encodes a file.
Package ops is the codec-free core of github.com/go-images/images: every pixel operation (resize, convolution, blurs, edges, morphology, colour, geometric transforms, warps, the raster facades) and nothing that decodes or encodes a file.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址