cv Module (stx.cv)

scitex-cv — small cv2-based image utilities (standalone).

Provides reusable cv2-based utilities for image processing: - I/O: load, save, color conversions - Transform: resize, rotate, flip, crop, pad - Filters: blur, sharpen, edge detection, threshold, denoise - Draw: rectangle, circle, line, text, polylines, arrow - OCR: ocr (image -> text via EasyOCR; optional ocr extra) - OCR: ocr_surya (image -> structured layout+text via a Surya-2 llama-server;

no torch, so it runs on GPUs current torch wheels ship no kernels for)

Example

>>> import scitex.cv as cv
>>> # Load and process an image
>>> img = cv.load("input.png")
>>> img = cv.resize(img, scale=0.5)
>>> img = cv.blur(img, ksize=5)
>>> edges = cv.edge_detect(img, method="canny")
>>> cv.save(edges, "edges.png")
scitex.cv.load(path, color=True, alpha=False)[source]

Load an image from file.

Parameters:
  • path (Union[str, Path]) – Image file path.

  • color (bool) – If True, load as color (BGR). If False, load as grayscale.

  • alpha (bool) – If True, preserve alpha channel (BGRA).

Returns:

Image array in BGR or grayscale format.

Return type:

ndarray

scitex.cv.save(img, path, quality=95)[source]

Save an image to file.

Parameters:
  • img (ndarray) – Image array (BGR or grayscale).

  • path (Union[str, Path]) – Output file path.

  • quality (int) – JPEG quality (0-100) or PNG compression (0-9).

Returns:

Path to saved file.

Return type:

Path

scitex.cv.to_rgb(img)[source]

Convert BGR image to RGB.

Parameters:

img (ndarray) – BGR image.

Returns:

RGB image.

Return type:

ndarray

scitex.cv.to_bgr(img)[source]

Convert RGB image to BGR.

Parameters:

img (ndarray) – RGB image.

Returns:

BGR image.

Return type:

ndarray

scitex.cv.to_gray(img)[source]

Convert image to grayscale.

Parameters:

img (ndarray) – Color image (BGR or RGB).

Returns:

Grayscale image.

Return type:

ndarray

scitex.cv.resize(img, size=None, scale=None, interpolation='linear')[source]

Resize an image.

Parameters:
  • img (ndarray) – Input image.

  • size (Optional[Tuple[int, int]]) – Target size as (width, height).

  • scale (Optional[float]) – Scale factor (alternative to size).

  • interpolation (str) – Interpolation method: ‘nearest’, ‘linear’, ‘cubic’, ‘area’, ‘lanczos’.

Returns:

Resized image.

Return type:

ndarray

scitex.cv.rotate(img, angle, center=None, scale=1.0)[source]

Rotate an image.

Parameters:
  • img (ndarray) – Input image.

  • angle (float) – Rotation angle in degrees (counter-clockwise).

  • center (Optional[Tuple[int, int]]) – Rotation center. Defaults to image center.

  • scale (float) – Scale factor.

Returns:

Rotated image.

Return type:

ndarray

scitex.cv.flip(img, direction='horizontal')[source]

Flip an image.

Parameters:
  • img (ndarray) – Input image.

  • direction (str) – Flip direction: ‘horizontal’, ‘vertical’, or ‘both’.

Returns:

Flipped image.

Return type:

ndarray

scitex.cv.crop(img, x, y, width, height)[source]

Crop a region from an image.

Parameters:
  • img (ndarray) – Input image.

  • x (int) – Top-left corner coordinates.

  • y (int) – Top-left corner coordinates.

  • width (int) – Crop dimensions.

  • height (int) – Crop dimensions.

Returns:

Cropped image.

Return type:

ndarray

scitex.cv.pad(img, top=0, bottom=0, left=0, right=0, color=0, mode='constant')[source]

Pad an image.

Parameters:
  • img (ndarray) – Input image.

  • top (int) – Padding sizes.

  • bottom (int) – Padding sizes.

  • left (int) – Padding sizes.

  • right (int) – Padding sizes.

  • color (Union[int, Tuple[int, ...]]) – Padding color for constant mode.

  • mode (str) – Padding mode: ‘constant’, ‘reflect’, ‘replicate’.

Returns:

Padded image.

Return type:

ndarray

scitex.cv.blur(img, ksize=5, method='gaussian')[source]

Apply blur to an image.

Parameters:
  • img (ndarray) – Input image.

  • ksize (int) – Kernel size (must be odd).

  • method (str) – Blur method: ‘gaussian’, ‘median’, ‘box’, ‘bilateral’.

Returns:

Blurred image.

Return type:

ndarray

scitex.cv.sharpen(img, strength=1.0)[source]

Sharpen an image.

Parameters:
  • img (ndarray) – Input image.

  • strength (float) – Sharpening strength.

Returns:

Sharpened image.

Return type:

ndarray

scitex.cv.edge_detect(img, method='canny', low=50, high=150)[source]

Detect edges in an image.

Parameters:
  • img (ndarray) – Input image.

  • method (str) – Edge detection method: ‘canny’, ‘sobel’, ‘laplacian’.

  • low (int) – Thresholds for Canny detector.

  • high (int) – Thresholds for Canny detector.

Returns:

Edge image.

Return type:

ndarray

scitex.cv.threshold(img, thresh=127, maxval=255, method='binary')[source]

Apply thresholding to an image.

Parameters:
  • img (ndarray) – Input image.

  • thresh (int) – Threshold value.

  • maxval (int) – Maximum value.

  • method (str) – Threshold method: ‘binary’, ‘binary_inv’, ‘trunc’, ‘tozero’, ‘tozero_inv’, ‘otsu’, ‘adaptive_mean’, ‘adaptive_gaussian’.

Returns:

Thresholded image.

Return type:

ndarray

scitex.cv.denoise(img, strength=10, method='fastNl')[source]

Denoise an image.

Parameters:
  • img (ndarray) – Input image.

  • strength (int) – Denoising strength.

  • method (str) – Denoising method: ‘fastNl’, ‘bilateral’.

Returns:

Denoised image.

Return type:

ndarray

scitex.cv.rectangle(img, pt1, pt2, color=(0, 255, 0), thickness=2, filled=False)[source]

Draw a rectangle on an image.

Parameters:
  • img (ndarray) – Input image (modified in place).

  • pt1 (Tuple[int, int]) – Top-left corner (x, y).

  • pt2 (Tuple[int, int]) – Bottom-right corner (x, y).

  • color (Tuple[int, int, int]) – BGR color.

  • thickness (int) – Line thickness (-1 for filled).

  • filled (bool) – If True, fill the rectangle.

Returns:

Image with rectangle.

Return type:

ndarray

scitex.cv.circle(img, center, radius, color=(0, 255, 0), thickness=2, filled=False)[source]

Draw a circle on an image.

Parameters:
  • img (ndarray) – Input image (modified in place).

  • center (Tuple[int, int]) – Center coordinates (x, y).

  • radius (int) – Circle radius.

  • color (Tuple[int, int, int]) – BGR color.

  • thickness (int) – Line thickness.

  • filled (bool) – If True, fill the circle.

Returns:

Image with circle.

Return type:

ndarray

scitex.cv.line(img, pt1, pt2, color=(0, 255, 0), thickness=2)[source]

Draw a line on an image.

Parameters:
Returns:

Image with line.

Return type:

ndarray

scitex.cv.text(img, text, position, color=(255, 255, 255), scale=1.0, thickness=2, font='simplex')[source]

Draw text on an image.

Parameters:
  • img (ndarray) – Input image (modified in place).

  • text (str) – Text to draw.

  • position (Tuple[int, int]) – Bottom-left corner of text (x, y).

  • color (Tuple[int, int, int]) – BGR color.

  • scale (float) – Font scale.

  • thickness (int) – Text thickness.

  • font (str) – Font type: ‘simplex’, ‘plain’, ‘duplex’, ‘complex’, ‘triplex’.

Returns:

Image with text.

Return type:

ndarray

scitex.cv.polylines(img, points, closed=True, color=(0, 255, 0), thickness=2)[source]

Draw polylines on an image.

Parameters:
  • img (ndarray) – Input image (modified in place).

  • points (ndarray) – Array of points with shape (N, 1, 2) or (N, 2).

  • closed (bool) – Whether to close the polyline.

  • color (Tuple[int, int, int]) – BGR color.

  • thickness (int) – Line thickness.

Returns:

Image with polylines.

Return type:

ndarray

scitex.cv.arrow(img, pt1, pt2, color=(0, 255, 0), thickness=2, tip_length=0.1)[source]

Draw an arrowed line on an image.

Parameters:
  • img (ndarray) – Input image (modified in place).

  • pt1 (Tuple[int, int]) – Start point (x, y).

  • pt2 (Tuple[int, int]) – End point (arrow tip) (x, y).

  • color (Tuple[int, int, int]) – BGR color.

  • thickness (int) – Line thickness.

  • tip_length (float) – Arrow tip length as fraction of line length.

Returns:

Image with arrow.

Return type:

ndarray

scitex.cv.ocr(image, languages=('ja', 'en'), detail=False, gpu=None)[source]

Recognize text in an image.

Parameters:
  • image (Union[str, Path, ndarray]) – A path to an image file, or an in-memory image array. Arrays may be BGR (cv2’s native order, as produced by scitex_cv.load()) or RGB / grayscale — EasyOCR handles any of these numpy inputs directly.

  • languages (Sequence[str]) – Language codes to recognize (EasyOCR codes, e.g. "en", "ja"). Defaults to Japanese + English. The set is used as the cache key for the underlying model, so the same tuple reuses one loaded Reader.

  • detail (bool) – If False (default), return the recognized text pieces concatenated into a single string. If True, return the raw list of (bbox, text, confidence) tuples EasyOCR yields.

  • gpu (Optional[bool]) – Whether EasyOCR should use CUDA. Left as None (the default) it is decided by torch_build_has_kernels_for_local_gpu(), NOT by EasyOCR’s own default of True. EasyOCR trusts torch.cuda.is_available(), which answers True on cards this torch build ships no kernels for (a GTX 1070 being the measured case), so the default selects a GPU that cannot run the model. Pass True or False to override the probe.

Returns:

Concatenated recognized text (detail=False) or the list of (bbox, text, confidence) tuples (detail=True).

Return type:

Union[str, List[Tuple]]

Raises:
  • TypeError – If image is neither a path-like nor a numpy array.

  • ImportError – If EasyOCR is not installed (install scitex-cv[ocr]).

scitex.cv.torch_build_has_kernels_for_local_gpu()[source]

Whether the INSTALLED TORCH BUILD ships kernels for THIS machine’s GPU.

Deliberately named after torch rather than after “GPU availability”, because the two are not the same question and conflating them is the bug this exists to prevent.

torch.cuda.is_available() answers “is there a working driver and runtime”, and on a GTX 1070 it returns True — while torch.cuda.get_arch_list() for torch 2.13.0+cu130 is sm_75/80/86/90/100/120 and the card is sm_61. The driver is fine; only the kernels for this card are missing. So the obvious probe reports a usable GPU and every torch-backed engine then selects one that cannot run. (Measured by the grant agent on scitex-compute-03, 2026-08-10.)

The name carries the scope boundary on purpose: this is a fact about a torch build, NOT about the card. Engines on other runtimes — CTranslate2, ONNX Runtime, llama.cpp — have their own kernel coverage and must not inherit this answer. In particular llama.cpp built with CMAKE_CUDA_ARCHITECTURES=61 runs perfectly well on the same card.

Returns False when torch is absent, since no torch build then has kernels for anything.

Return type:

bool

scitex.cv.ocr_surya(image, endpoint='http://127.0.0.1:18081/v1/chat/completions', prompt='Read all the text in this document.', max_tokens=4096, timeout=300.0, ladder=((1770, 'cubic'), (1770, 'area'), (1770, 'lanczos4'), (1755, 'cubic'), (1800, 'cubic'), (1740, 'area')))[source]

Read image via a running Surya llama-server.

Walks ladder, stopping at the first rendering whose response is not layout-only. A single rendering’s failure is NOT the page’s failure — 2 of 12 renderings recovered a soft scan that failed at its native size — so giving up after one attempt would discard readable pages. A crisp page reads on the first rung and costs nothing extra (measured 12 of 12).

Pass ladder=((height, filter),) for a single attempt, or ladder=() to send the source image untouched.

Returns a SuryaReading in every non-transport case, including when no rung read the page — the failure is data, not an exception, because “this page produced no characters” is a fact the caller routinely needs to record rather than crash on. rendering names the rung that was used and attempts how many were tried.

Raises:
  • TypeError – If image is neither path-like nor a numpy array.

  • ValueError – If a ladder rung names an unknown interpolation filter.

  • ConnectionError – If the endpoint could not be reached or answered malformed JSON. A transport failure genuinely is exceptional: it says nothing about the page, so returning a reading would misattribute it to the document.

Return type:

SuryaReading

class scitex.cv.SuryaReading(status, text, body, source_size, sent_size, image_tokens, rendering=None, attempts=1)[source]

Bases: object

What the eyes saw — always this shape, never a bare string.

status is the three-valued signal the caller must branch on:

"text"

Characters were recovered; text holds them.

"layout-only"

The model answered with block geometry and no characters. This is a FAILURE, not a page without text — see the module docstring. text is None, because “” would be indistinguishable from a genuinely blank page.

"empty"

The model returned nothing usable at all.

sent_size is the (width, height) actually transmitted after normalization, which is rarely the source size and is the number a caller needs in order to reason about a failure. No field names a cause: this engine does not know one, and inventing it would cross into interpretation the caller owns.

status: str
text: Optional[str]
body: str
source_size: Tuple[int, int]
sent_size: Tuple[int, int]
image_tokens: Optional[int]
rendering: Optional[Tuple[int, str]] = None
attempts: int = 1
property read: bool

True only when characters were actually recovered.

scitex.cv.normalize_page(image, height=1770, filter_name='cubic')[source]

Resample image so its long edge is height, preserving aspect.

Scales DOWN as readily as up — the point is to land on a rendering the model reads, not to maximise pixels. Upscaling a soft scan too far was measured to break recognition that worked at a smaller size.

filter_name matters and is not cosmetic: on the soft scan, cubic and area at height 1770 recovered the text while lanczos4 and linear at the same size did not. This is why ocr_surya() varies it across the ladder rather than fixing one filter.

Return type:

ndarray

scitex.cv.is_layout_only(body)[source]

True when the model returned block geometry instead of characters.

Mechanically decidable, which is the whole reason this failure is worth detecting: the response is a JSON array of {label, bbox, count} objects carrying no text, and it arrives with finish_reason="stop" and a plausible byte count. It reads as success to anything that only checks that the request completed.

Return type:

bool

scitex.cv.read_document(path, endpoint='http://127.0.0.1:18081/v1/chat/completions', prompt='Read all the text in this document.', ladder=((1770, 'cubic'), (1770, 'area'), (1770, 'lanczos4'), (1755, 'cubic'), (1800, 'cubic'), (1740, 'area')), force=False, max_tokens=4096, timeout=300.0)[source]

Read every page of path, resuming from a sidecar when one exists.

Re-running a document that already has a sidecar is a NO-OP for pages that were resolved, unless force. That is what makes an overnight batch survivable.

A PDF page carrying a real text layer is taken from that layer and OCR is skipped entirely — faster and more accurate — recording source="pdf-text-layer" so the caller can tell which path ran.

Returns:

Always. A page that cannot be processed becomes an error page rather than an exception: one bad page in a 300-page scan must not discard the other 299. Only a document that cannot be OPENED raises.

Return type:

DocumentReading

class scitex.cv.DocumentReading(path, page_count, pages, ladder)[source]

Bases: object

Ordered per-page results for one input file.

Page-level rather than document-level by request: filing rules key off page 1, and a 20-page register extract must not collapse into one blob.

path: str
page_count: int
pages: Tuple[PageReading, ...]
ladder: Tuple[Tuple[int, str], ...]
property unread_pages: Tuple[int, ...]

Indices that produced no characters, for any reason.

class scitex.cv.PageReading(index, status, text, source, rendering, image_tokens, attempts, detail=None)[source]

Bases: object

What was observed on one page. Never a bare string.

text is non-None if and only if status == "text" — enforced in __post_init__, so a caller may branch on either and get the same answer. source says which path produced it (pdf-text-layer or ocr), which the consumer asked for explicitly.

index: int
status: str
text: Optional[str]
source: Optional[str]
rendering: Optional[Tuple[int, str]]
image_tokens: Optional[int]
attempts: int
detail: Optional[str] = None
property read: bool

True only when characters were recovered. A blank page is not read.

scitex.cv.sidecar_path_for(document_path)[source]

Where the sidecar for document_path lives. Stable and adjacent.

Return type:

Path