diff --git a/tests/base/test_color_convertflag.py b/tests/base/test_color_convertflag.py new file mode 100644 index 00000000..5f76483b --- /dev/null +++ b/tests/base/test_color_convertflag.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +"""Tests of the colorspace name -> OpenCV conversion code table, and of the Lab +chromaticity-diagram background image.""" + +import cv2 +import numpy as np +import pytest + +from machinevisiontoolbox.base.color import _ab_chromaticity_diagram, _convertflag + +# (source, destination, OpenCV constant) for every conversion the table supports +FROM_RGB = [ + ("grey", "COLOR_RGB2GRAY"), + ("gray", "COLOR_RGB2GRAY"), + ("xyz", "COLOR_RGB2XYZ"), + ("xyz_709", "COLOR_RGB2XYZ"), + ("ycrcb", "COLOR_RGB2YCrCb"), + ("hsv", "COLOR_RGB2HSV"), + ("hls", "COLOR_RGB2HLS"), + ("lab", "COLOR_RGB2Lab"), + ("l*a*b*", "COLOR_RGB2Lab"), + ("luv", "COLOR_RGB2Luv"), + ("l*u*v*", "COLOR_RGB2Luv"), +] +FROM_BGR = [(dst, name.replace("RGB2", "BGR2")) for dst, name in FROM_RGB] +TO_RGB_OR_BGR = [ + ("xyz", "XYZ"), + ("xyz_709", "XYZ"), + ("ycrcb", "YCrCb"), + ("hsv", "HSV"), + ("hls", "HLS"), + ("lab", "Lab"), + ("l*a*b*", "Lab"), + ("luv", "Luv"), + ("l*u*v*", "Luv"), +] + + +class TestConvertFlag: + @pytest.mark.parametrize("dst, name", FROM_RGB) + def test_from_rgb(self, dst, name): + assert _convertflag("rgb", dst) == getattr(cv2, name) + + @pytest.mark.parametrize("dst, name", FROM_BGR) + def test_from_bgr(self, dst, name): + assert _convertflag("bgr", dst) == getattr(cv2, name) + + @pytest.mark.parametrize("src, space", TO_RGB_OR_BGR) + def test_to_rgb(self, src, space): + assert _convertflag(src, "rgb") == getattr(cv2, f"COLOR_{space}2RGB") + + @pytest.mark.parametrize("src, space", TO_RGB_OR_BGR) + def test_to_bgr(self, src, space): + assert _convertflag(src, "bgr") == getattr(cv2, f"COLOR_{space}2BGR") + + def test_names_ignore_case_and_colons(self): + assert _convertflag("RGB", "HSV") == cv2.COLOR_RGB2HSV + assert _convertflag("R:G:B", "Lab") == cv2.COLOR_RGB2Lab + assert _convertflag("B:G:R", "Gray") == cv2.COLOR_BGR2GRAY + + def test_unknown_destination_from_rgb(self): + with pytest.raises(ValueError, match="not known"): + _convertflag("rgb", "cmyk") + + @pytest.mark.parametrize( + "src, dst", + [ + ("bgr", "cmyk"), # unknown destination from bgr + ("hsv", "lab"), # only conversions to rgb and bgr exist + ("lab", "hsv"), + ("grey", "rgb"), # no way back from grey + ("cmyk", "rgb"), # unknown source + ("xyz", "ycrcb"), + ], + ) + def test_unsupported_conversions_raise(self, src, dst): + with pytest.raises(ValueError, match="unknown conversion"): + _convertflag(src, dst) + + +class TestAbChromaticityDiagram: + def test_shape_and_range(self): + img = _ab_chromaticity_diagram(L=70, N=64) + assert img.shape == (64, 64, 3) + assert img.min() >= 0 and img.max() <= 1 + + def test_outside_the_gamut_circle_is_white(self): + img = _ab_chromaticity_diagram(N=64) + for corner in (img[0, 0], img[0, -1], img[-1, 0], img[-1, -1]): + np.testing.assert_array_equal(corner, [1, 1, 1]) + + def test_centre_is_neutral(self): + # a = b = 0 is grey: equal red, green and blue + img = _ab_chromaticity_diagram(L=50, N=65) + centre = img[32, 32] + assert np.ptp(centre) < 0.05 + + def test_a_axis_runs_left_to_right(self): + # green (negative a) on the left, red (positive a) on the right + img = _ab_chromaticity_diagram(L=60, N=65) + left, right = img[32, 20], img[32, 44] + assert left[1] > left[0] + assert right[0] > right[1] + + def test_b_axis_runs_bottom_to_top(self): + # blue (negative b) at the bottom, yellow (positive b) at the top: the + # image is flipped so that b increases upwards + img = _ab_chromaticity_diagram(L=60, N=65) + top, bottom = img[20, 32], img[44, 32] + assert top[2] < top[0] + assert bottom[2] > bottom[0] diff --git a/tests/base/test_color_shadow.py b/tests/base/test_color_shadow.py new file mode 100644 index 00000000..c6daafb8 --- /dev/null +++ b/tests/base/test_color_shadow.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python +"""Tests of shadow_invariant() and esttheta(). + +A synthetic image is built so that the right answer is known. Pixels of one material +that are lit or in shadow differ only in their position along a line in the +log-chromaticity plane; the line perpendicular to it, at angle ``theta``, is the +invariant direction. So projecting onto ``theta`` gives the same grey value for every +pixel, and sweeping the angle finds ``theta`` again. The one thing replaced in +esttheta() is the user's mouse clicks on the region. +""" + +import matplotlib +import matplotlib.pyplot as plt +import numpy as np +import numpy.testing as nt +import pytest +from matplotlib.figure import Figure + +from machinevisiontoolbox import Image +from machinevisiontoolbox.base.color import esttheta, shadow_invariant + +THETA = 0.7 # the invariant angle of the synthetic image, radians + + +def synthetic(theta=THETA, shape=(6, 40), d0=(0.2, -0.1)): + """Linear RGB image whose pixels differ only along the shadow direction. + + Returns the image and the grey value that the invariant should have everywhere. + """ + c = np.array([np.cos(theta), np.sin(theta)]) # the invariant direction + u = np.array([-np.sin(theta), np.cos(theta)]) # the direction shadows move pixels + t = np.linspace(-1, 1, shape[1]) + d = np.array(d0)[:, None] + u[:, None] * t # log chromaticities, (2, W) + r, b = np.exp(d) + g = 1 / (r * b) # makes the geometric mean of R, G, B equal to 1 + row = np.stack([r, g, b], axis=1) # (W, 3) + im = np.broadcast_to(row, (shape[0], shape[1], 3)).copy() + return im, float(np.dot(d0, c)) + + +class TestShadowInvariant: + def test_constant_for_lit_and_shadowed_pixels(self): + im, expected = synthetic() + gs = shadow_invariant(im, THETA) + assert gs.shape == im.shape[:2] + nt.assert_allclose(gs, expected, atol=1e-9) + + def test_wrong_angle_is_not_constant(self): + im, _ = synthetic() + gs = shadow_invariant(im, THETA + 0.5) + assert np.ptp(gs) > 0.1 + + def test_exp_exponentiates(self): + im, expected = synthetic() + nt.assert_allclose(shadow_invariant(im, THETA, exp=True), np.exp(expected)) + + def test_green_channel_as_denominator(self): + # without the geometric mean, the chromaticities are R/G and B/G + im, _ = synthetic() + rgb = im.reshape(-1, 3) + d = np.log(np.stack([rgb[:, 0] / rgb[:, 1], rgb[:, 2] / rgb[:, 1]])) + c = np.array([np.cos(THETA), np.sin(THETA)]) + gs = shadow_invariant(im, THETA, geometricmean=False) + nt.assert_allclose(gs.ravel(), d.T @ c) + + def test_identity_sharpening_changes_nothing(self): + im, _ = synthetic() + nt.assert_allclose( + shadow_invariant(im, THETA, sharpen=np.eye(3)), shadow_invariant(im, THETA) + ) + + def test_sharpening_is_applied(self): + im, _ = synthetic() + sharpen = np.array([[1.2, -0.1, -0.1], [-0.1, 1.2, -0.1], [-0.1, -0.1, 1.2]]) + assert not np.allclose( + shadow_invariant(im, THETA, sharpen=sharpen), shadow_invariant(im, THETA) + ) + + def test_default_angle_comes_from_the_camera_filters(self): + # with no angle, the direction is worked out from the peak responses of the + # Sony ICX204 sensor: 610, 538 and 460 nm + im, _ = synthetic() + c2 = 1.4388e-2 + e_r, e_b = -c2 / 610e-9, -c2 / 460e-9 + c = np.array([e_b, -e_r]) + c /= np.linalg.norm(c) + rgb = im.reshape(-1, 3) + denom = np.prod(rgb, axis=1) ** (1 / 3) + d = np.log(np.stack([rgb[:, 0] / denom, rgb[:, 2] / denom])) + nt.assert_allclose(shadow_invariant(im).ravel(), d.T @ c) + + @pytest.mark.xfail( + strict=True, + raises=UnboundLocalError, + reason="passing primaries without theta leaves the projection direction unset", + ) + def test_primaries_without_an_angle(self): + im, _ = synthetic() + shadow_invariant(im, primaries=np.array([600, 540, 450]) * 1e-9) + + def test_not_a_color_image_raises(self): + with pytest.raises(ValueError): + shadow_invariant(np.ones((4, 4)), THETA) + with pytest.raises(ValueError): + shadow_invariant(np.ones((4, 4, 4)), THETA) + + def test_zero_pixels_give_nan_not_an_exception(self): + im, _ = synthetic(shape=(2, 6)) + im[0, 0] = 0 + gs = shadow_invariant(im, THETA) + assert not np.isfinite(gs[0, 0]) + assert np.all(np.isfinite(gs[1])) + + +@pytest.fixture +def agg_backend(): + previous = matplotlib.get_backend() + plt.switch_backend("Agg") + yield + plt.close("all") + plt.switch_backend(previous) + + +class TestEstTheta: + """The region is picked with the mouse, so the clicks are supplied.""" + + def click_whole_image(self, monkeypatch, shape): + h, w = shape + corners = [(-0.5, -0.5), (w - 0.5, -0.5), (w - 0.5, h - 0.5), (-0.5, h - 0.5)] + monkeypatch.setattr(Figure, "ginput", lambda self, n=-1, **kw: corners) + + def test_recovers_the_invariant_angle(self, agg_backend, monkeypatch, capsys): + array, _ = synthetic() + self.click_whole_image(monkeypatch, array.shape[:2]) + theta = esttheta(Image(array, colororder="RGB")) + # the angle is searched in steps of 0.02 rad + assert theta == pytest.approx(THETA, abs=0.021) + out = capsys.readouterr().out + assert f"{array.shape[0] * array.shape[1]} pixels selected" in out + assert "best angle" in out + + def test_a_different_angle_is_found(self, agg_backend, monkeypatch): + array, _ = synthetic(theta=1.9) + self.click_whole_image(monkeypatch, array.shape[:2]) + assert esttheta(Image(array, colororder="RGB")) == pytest.approx(1.9, abs=0.021) + + def test_sharpening_is_accepted(self, agg_backend, monkeypatch): + array, _ = synthetic() + self.click_whole_image(monkeypatch, array.shape[:2]) + theta = esttheta(Image(array, colororder="RGB"), sharpen=np.eye(3)) + assert theta == pytest.approx(THETA, abs=0.021)