How to use assert_image method in toolium

Best Python code snippet using toolium_python

test_Goulib_image.py

Source:test_Goulib_image.py Github

copy

Full Screen

...6from skimage import data7import os8path = os.path.dirname(os.path.abspath(__file__))9results = path+'\\results\\image\\' # path for results10def assert_image(image, name=None, convert=False):11 """ Checks if an image is present (not black, white, or low contrast12 :param image: Image to check13 :param name: str, optional file name. image is saved is specified14 :param convert: bool specifies if image is converted to RGB for saving15 """16 from skimage.exposure import is_low_contrast17 if name:18 image.save(results+name, autoconvert=convert)19 if is_low_contrast(image.array):20 logging.warning('image %s has low contrast' % name)21class TestImage:22 @classmethod23 def setup_class(self):24 self.lena = Image(path+'/data/lena.png')25 assert_equal(self.lena, self.lena) # make sure image comparizon works26 assert_image(self.lena.grayscale('L'),27 'grayscale.png') # force to uint828 self.gray = Image(results+'grayscale.png')29 self.camera = Image(data.camera())30 def test_pdf(self):31 return # for now for speed32 try:33 import pdfminer34 except:35 return # pass36 assert_image(Image(path+'/data/lena.pdf'), 'pdf_out.png')37 assert_image(Image(path+'/data/Pantone Fan.pdf'), 'Pantone Fan.png')38 # Image(path+'/data/Pantone Fan CMYKOGB Equinox.pdf').save('Pantone Fan CMYKOGB Equinox.png')39 def test___init__(self):40 lena2 = Image(self.lena)41 assert_equal(self.lena, lena2)42 def test_generate(self):43 # from matrix44 from matplotlib import cm45 a = [[-x*x+y*y for x in range(128)] for y in range(128)]46 a = normalize(a)47 assert_image(Image(a), 'generated.png')48 assert_image(Image(a, colormap=cm.get_cmap('nipy_spectral')),49 'gen_colormap.png', True)50 def test___hash__(self):51 h1 = hash(self.lena)52 h2 = hash(self.gray)53 diff = h1 ^ h2 # XOR54 diff = math2.digsum(diff, 2) # number of different pixels55 assert_equal(h1, h2, msg='difference is %d pixels' % diff)56 57 def test_dist(self):58 assert_equal(self.lena.dist(self.gray),0)59 60 s=self.lena.size;61 lena2=self.lena.resize((s[0],s[1]*2))62 lena2.save(results+'lena.2.width.png')63 64 tol=4/64 # don't know why...65 66 d=self.lena.dist(lena2)67 68 assert_true(d<=tol)69 70 for method in [AVERAGE, PERCEPTUAL]:71 72 assert_true(self.lena.dist(lena2,method)<=tol)73 74 assert_true(self.lena.dist(lena2.flip(),method,symmetries=True)<=tol)75 assert_true(self.lena.dist(lena2.flip(False,True),method,symmetries=True)<=tol)76 def test___getitem__(self):77 pixel = self.gray[256, 256]78 assert_equal(pixel, 90)79 pixel = self.lena[256, 256]80 # (180,65,72))81 assert_equal(pixel, [0.70588235, 0.25490196, 0.28235294])82 left = self.lena[:, :256]83 right = self.lena[:, 256:-1]84 face = self.lena[246:374, 225:353]85 assert_image(face, 'lena.face.png')86 face = face.grayscale()87 eye = face[3:35, -35:-3] # negative indexes are handy in some cases88 c = face.correlation(eye)89 # assert_image(c,"correlation.png")90 def test___lt__(self):91 # image = Image(data)92 # assert_equal(expected, image.__lt__(other))93 raise SkipTest94 def test___repr__(self):95 assert_true(repr(self.lena) in [96 'Image(mode=RGB shape=(512, 512, 3) type=float64)',97 # with some versions98 'Image(mode=RGB shape=(512L, 512L, 3L) type=float64)',99 ]100 )101 def test_mode(self):102 pass # useless ?103 def test_open(self):104 lena3 = Image.open(path+'/data/lena.png')105 assert_equal(self.lena, lena3)106 def test_html(self):107 pass # do not implement this one as it requires IPython108 def test__repr_html_(self):109 h = self.lena.convert('P')._repr_html_()110 assert_true(h)111 def test_average_hash(self):112 h1 = self.lena.average_hash()113 h2 = self.gray.average_hash()114 assert_equal(h1, h2)115 def test_perceptual_hash(self):116 h1 = self.lena.perceptual_hash()117 h2 = self.gray.perceptual_hash()118 assert_equal(h1, h2)119 def test_base64(self):120 # image = Image(data, **kwargs)121 # assert_equal(expected, image.base64(fmt))122 raise SkipTest # implement your test here123 def test_grayscale(self):124 pass125 def test_invert(self):126 # image = Image(data, **kwargs)127 # assert_equal(expected, image.invert())128 raise SkipTest # implement your test here129 def test_ndarray(self):130 pass131 def test_render(self):132 # same as h(self.lena) but without IPython133 h = self.lena.render()134 assert_true(h)135 """136 def test_convert(self):137 for mode in modes:138 im = self.lena.convert(mode)139 assert_image(im, 'convert_%s.png' % mode)140 try:141 im2 = im.convert('RGB')142 assert_image(im2, 'convert_%s_round_trip.png' % mode)143 except Exception as e:144 logging.error(145 '%s round trip conversion failed with %s' % (mode, e))146 im2 = im.convert('RGB')147 """148 def test_split(self):149 rgb = self.lena.split()150 for im, c in zip(rgb, 'RGB'):151 assert_image(im, 'split_%s.png' % c)152 assert_image(Image(rgb), 'RGB_merge.png')153 colors = ['Cyan', 'Magenta', 'Yellow', 'blacK']154 cmyk = self.lena.split('CMYK')155 cmyk2 = [im.colorize(col) for im, col in zip(cmyk, colors)]156 for im, c in zip(cmyk2, 'CMYK'):157 assert_image(im, 'split_%s.png' % c)158 assert_image(Image(cmyk, mode='CMYK'), 'CMYK_merge.png')159 lab = self.lena.split('Lab')160 for im, c in zip(lab, 'LAB'):161 assert_image(im, 'split_%s.png' % c)162 lab = Image(lab, mode='LAB')163 assert_image(lab, 'Lab.png')164 def test_filter(self):165 from PIL.ImageFilter import BLUR, CONTOUR, DETAIL, EDGE_ENHANCE, EDGE_ENHANCE_MORE, EMBOSS, FIND_EDGES, SMOOTH, SMOOTH_MORE, SHARPEN166 for f in [BLUR, CONTOUR, DETAIL, EDGE_ENHANCE, EDGE_ENHANCE_MORE, EMBOSS, FIND_EDGES, SMOOTH, SMOOTH_MORE, SHARPEN]:167 r = self.lena.filter(f)168 assert_image(r, 'filter_pil_%s.png' % f.__name__)169 from skimage.filters import sobel, prewitt, scharr, roberts170 from skimage.restoration import denoise_bilateral171 for f in [sobel, prewitt, scharr, roberts, denoise_bilateral, ]:172 try:173 assert_image(self.lena.filter(174 f), 'filter_sk_%s.png' % f.__name__)175 except:176 pass177 def test_dither(self):178 for k in dithering:179 im = self.gray.dither(k)*255180 assert_image(im, 'dither_%s.png' % dithering[k])181 assert_image(self.lena.dither(), 'dither_color_2.png')182 assert_image(self.lena.dither(n=4), 'dither_color_4.png')183 def test_resize(self):184 size = 128185 im = self.lena.resize((size, size))186 assert_image(im, 'resize_%d.png' % size)187 im = self.camera.resize((size, size))188 assert_image(im, 'camera_resize_%d.png' % size)189 def test_expand(self):190 size = 128191 im = self.lena.resize((size, size))192 # can you see that half pixel border ?193 im = im.expand((size+1, size+1), .5, .5)194 assert_image(im, 'expand_0.5 border.png')195 def test_add(self):196 dot = disk(20)197 im = Image()198 for i in range(3):199 for j in range(3):200 im = im.add(dot, (j*38.5, i*41.5), 0.5)201 assert_image(im, 'image_add.png')202 def test_colorize(self):203 cmyk = self.lena.split('CMYK')204 colors = ['Cyan', 'Magenta', 'Yellow', 'blacK']205 cmyk2 = [im.colorize(col) for im, col in zip(cmyk, colors)]206 # what a strange syntax ...207 back = cmyk2[0]-(-cmyk2[1])-(-cmyk2[2])-(-cmyk2[3])208 assert_image(back, 'image_add_sum_cmyk.png')209 assert_equal(self.lena.dist(back), 0)210 def test_mul(self):211 mask = disk(self.lena.size[0]/2)212 res = self.lena*mask213 assert_image(res, 'disk_mul.png')214 def test_shift(self):215 left = self.lena[:, 0:256]216 right = self.lena[:, 256:]217 blank = Image(size=(513, 513), mode='RGB', color='white')218 blank.paste(left, (0, 0))219 blank.paste(right.shift(1, 1), (256, 0))220 assert_image(blank, 'image_stitched.png')221 def test___abs__(self):222 # image = Image(data, mode, **kwargs)223 # assert_equal(expected, image.__abs__())224 raise SkipTest # implement your test here225 def test___add__(self):226 # image = Image(data, mode, **kwargs)227 # assert_equal(expected, image.__add__(other))228 raise SkipTest # implement your test here229 def test___div__(self):230 # image = Image(data, mode, **kwargs)231 # assert_equal(expected, image.__div__(f))232 raise SkipTest # implement your test here233 def test___mul__(self):234 # image = Image(data, mode, **kwargs)...

Full Screen

Full Screen

loaders_test.py

Source:loaders_test.py Github

copy

Full Screen

...8import numpy as np9from PIL import Image10from tifffile import TiffFile, TiffWriter, imwrite11from deepcell_label.loaders import Loader12def assert_image(archive, expected):13 """Assert that image is as expected."""14 # TZCYXS dimension order with squeeze=False15 image = TiffFile(archive.open('X.ome.tiff')).asarray(squeeze=False)16 # Drop the T and S dimension and move C to last dimension17 image = image[0, :, :, :, :, 0]18 image = np.moveaxis(image, 1, -1)19 np.testing.assert_array_equal(image, expected)20def assert_segmentation(archive, expected):21 """Assert that segmentation is as expected."""22 segmentation = TiffFile(archive.open('y.ome.tiff')).asarray(squeeze=False)23 # Drop the T and S dimension and move C to last dimension24 segmentation = segmentation[0, :, :, :, :, 0]25 segmentation = np.moveaxis(segmentation, 1, -1)26 np.testing.assert_array_equal(segmentation, expected)27 assert json.loads(archive.open('cells.json').read()) is not None28def test_load_npz():29 """Load npz with image data."""30 expected = np.zeros((1, 1, 1, 1))31 with tempfile.NamedTemporaryFile() as images:32 np.savez(images, X=expected)33 images.seek(0)34 loader = Loader(images)35 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))36 assert_image(loaded_zip, expected)37def test_load_two_channel_npz():38 """Load npz with image data with two channels."""39 expected = np.zeros((1, 100, 100, 2))40 with tempfile.NamedTemporaryFile() as images:41 np.savez(images, X=expected)42 images.seek(0)43 loader = Loader(images)44 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))45 assert_image(loaded_zip, expected)46def test_load_npz_with_segmentation():47 """Loads npz with image and segmentation."""48 expected_image = np.zeros((1, 1, 1, 1))49 expected_segmentation = np.ones((1, 1, 1, 1))50 with tempfile.NamedTemporaryFile() as images:51 np.savez(images, X=expected_image, y=expected_segmentation)52 images.seek(0)53 loader = Loader(images)54 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))55 assert_image(loaded_zip, expected_image)56 assert_segmentation(loaded_zip, expected_segmentation)57def test_load_separate_npz():58 """Loads image and segmentation from separate npz."""59 expected_image = np.zeros((1, 1, 1, 1))60 expected_segmentation = np.ones((1, 1, 1, 1))61 with tempfile.NamedTemporaryFile() as images, tempfile.NamedTemporaryFile() as labels:62 np.savez(images, X=expected_image)63 np.savez(labels, y=expected_segmentation)64 loader = Loader(images, labels)65 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))66 assert_image(loaded_zip, expected_image)67 assert_segmentation(loaded_zip, expected_segmentation)68def test_load_image_tiff():69 """Load image from tiff file."""70 expected = np.zeros((1, 1, 1, 1))71 with tempfile.NamedTemporaryFile() as images:72 with TiffWriter(images) as writer:73 writer.write(expected)74 images.seek(0)75 loader = Loader(images)76 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))77 assert_image(loaded_zip, expected)78def test_load_image_and_segmentation_tiff():79 """Load image from a tiff and labeled array a zipped tiff."""80 expected_image = np.zeros((1, 1, 1, 1))81 expected_segmentation = np.ones((1, 1, 1, 1))82 with tempfile.NamedTemporaryFile() as images, tempfile.NamedTemporaryFile() as labels:83 with TiffWriter(images) as writer:84 writer.write(expected_image)85 images.seek(0)86 with zipfile.ZipFile(labels, mode='w') as zf:87 tiff = io.BytesIO()88 with TiffWriter(tiff) as writer:89 writer.write(np.array([[1]]))90 tiff.seek(0)91 zf.writestr('feature0.tiff', tiff.read())92 loader = Loader(images, labels)93 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))94 assert_image(loaded_zip, expected_image)95 assert_segmentation(loaded_zip, expected_segmentation)96def test_load_image_png():97 """Load image array from png file."""98 expected = np.zeros((1, 1, 1, 1))99 with tempfile.NamedTemporaryFile() as images:100 img = Image.fromarray(np.zeros((1, 1)), mode='L')101 img.save(images, format='png')102 images.seek(0)103 loader = Loader(images)104 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))105 assert_image(loaded_zip, expected)106def test_load_image_zip():107 """Load image array from zip of tiff files."""108 expected_image = np.zeros((1, 100, 100, 2))109 with tempfile.NamedTemporaryFile() as images:110 def make_tiff(array):111 tiff = io.BytesIO()112 with TiffWriter(tiff) as writer:113 writer.write(array)114 tiff.seek(0)115 return tiff.read()116 with zipfile.ZipFile(images, mode='w') as zf:117 with zf.open('channel0.tiff', 'w') as tiff:118 channel_0 = make_tiff(np.zeros((1, 100, 100)))119 tiff.write(channel_0)120 with zf.open('channel1.tiff', 'w') as tiff:121 channel_1 = make_tiff(np.zeros((1, 100, 100)))122 tiff.write(channel_1)123 images.seek(0)124 loader = Loader(images)125 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))126 assert_image(loaded_zip, expected_image)127def test_load_segmentation_zip():128 """Load labeled array from zip of tiff files."""129 expected_image = np.zeros((1, 100, 100, 2))130 expected_segmentation = np.zeros((1, 100, 100, 2))131 with tempfile.NamedTemporaryFile() as images, tempfile.NamedTemporaryFile() as labels:132 def make_tiff(array):133 tiff = io.BytesIO()134 with TiffWriter(tiff) as writer:135 writer.write(array)136 tiff.seek(0)137 return tiff.read()138 with zipfile.ZipFile(images, mode='w') as zf:139 with zf.open('channel_0.tiff', 'w') as tiff:140 channel_0 = make_tiff(np.zeros((1, 100, 100)))141 tiff.write(channel_0)142 with zf.open('channel_1.tiff', 'w') as tiff:143 channel_1 = make_tiff(np.zeros((1, 100, 100)))144 tiff.write(channel_1)145 images.seek(0)146 with zipfile.ZipFile(labels, mode='w') as zf:147 with zf.open('feature_0.tiff', 'w') as tiff:148 feature_0 = make_tiff(np.zeros((1, 100, 100)))149 tiff.write(feature_0)150 with zf.open('feature_1.tiff', 'w') as tiff:151 feature_1 = make_tiff(np.zeros((1, 100, 100)))152 tiff.write(feature_1)153 labels.seek(0)154 loader = Loader(images, labels)155 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))156 assert_image(loaded_zip, expected_image)157 assert_segmentation(loaded_zip, expected_segmentation)158def test_load_batches():159 """Load labeled array from zip of tiff files with multiple batches."""160 expected_image = np.zeros((2, 100, 100, 1))161 expected_segmentation = np.zeros((2, 100, 100, 1))162 expected_segmentation[1, :, :, :] = 1163 with tempfile.NamedTemporaryFile() as images, tempfile.NamedTemporaryFile() as labels:164 def make_tiff(array):165 tiff = io.BytesIO()166 imwrite(tiff, array)167 tiff.seek(0)168 return tiff.read()169 images.write(make_tiff(np.zeros((2, 100, 100, 1))))170 images.seek(0)171 with zipfile.ZipFile(labels, mode='w') as zf:172 with zf.open('batch_0_feature_0.tiff', 'w') as tiff:173 tiff.write(make_tiff(np.zeros((100, 100))))174 with zf.open('batch_1_feature_0.tiff', 'w') as tiff:175 tiff.write(make_tiff(np.zeros((100, 100)) + 1))176 labels.seek(0)177 loader = Loader(images, labels, 'BYXC')178 loaded_zip = zipfile.ZipFile(io.BytesIO(loader.data))179 assert_image(loaded_zip, expected_image)...

Full Screen

Full Screen

test_numpy.py

Source:test_numpy.py Github

copy

Full Screen

...24 if list(i.getchannel(0).getdata()) != list(range(100)):25 print("data mismatch for", dtype)26 return i27 # Check supported 1-bit integer formats28 assert_image(to_image(bool, 1, 1), "1", TEST_IMAGE_SIZE)29 assert_image(to_image(numpy.bool8, 1, 1), "1", TEST_IMAGE_SIZE)30 # Check supported 8-bit integer formats31 assert_image(to_image(numpy.uint8), "L", TEST_IMAGE_SIZE)32 assert_image(to_image(numpy.uint8, 3), "RGB", TEST_IMAGE_SIZE)33 assert_image(to_image(numpy.uint8, 4), "RGBA", TEST_IMAGE_SIZE)34 assert_image(to_image(numpy.int8), "I", TEST_IMAGE_SIZE)35 # Check non-fixed-size integer types36 # These may fail, depending on the platform, since we have no native37 # 64-bit int image types.38 # assert_image(to_image(numpy.uint), "I", TEST_IMAGE_SIZE)39 # assert_image(to_image(numpy.int), "I", TEST_IMAGE_SIZE)40 # Check 16-bit integer formats41 if Image._ENDIAN == "<":42 assert_image(to_image(numpy.uint16), "I;16", TEST_IMAGE_SIZE)43 else:44 assert_image(to_image(numpy.uint16), "I;16B", TEST_IMAGE_SIZE)45 assert_image(to_image(numpy.int16), "I", TEST_IMAGE_SIZE)46 # Check 32-bit integer formats47 assert_image(to_image(numpy.uint32), "I", TEST_IMAGE_SIZE)48 assert_image(to_image(numpy.int32), "I", TEST_IMAGE_SIZE)49 # Check 64-bit integer formats50 with pytest.raises(TypeError):51 to_image(numpy.uint64)52 with pytest.raises(TypeError):53 to_image(numpy.int64)54 # Check floating-point formats55 assert_image(to_image(float), "F", TEST_IMAGE_SIZE)56 with pytest.raises(TypeError):57 to_image(numpy.float16)58 assert_image(to_image(numpy.float32), "F", TEST_IMAGE_SIZE)59 assert_image(to_image(numpy.float64), "F", TEST_IMAGE_SIZE)60 assert_image(to_image(numpy.uint8, 2), "LA", (10, 10))61 assert_image(to_image(numpy.uint8, 3), "RGB", (10, 10))62 assert_image(to_image(numpy.uint8, 4), "RGBA", (10, 10))63# Based on an erring example at64# https://stackoverflow.com/questions/10854903/what-is-causing-dimension-dependent-attributeerror-in-pil-fromarray-function65def test_3d_array():66 size = (5, TEST_IMAGE_SIZE[0], TEST_IMAGE_SIZE[1])67 a = numpy.ones(size, dtype=numpy.uint8)68 assert_image(Image.fromarray(a[1, :, :]), "L", TEST_IMAGE_SIZE)69 size = (TEST_IMAGE_SIZE[0], 5, TEST_IMAGE_SIZE[1])70 a = numpy.ones(size, dtype=numpy.uint8)71 assert_image(Image.fromarray(a[:, 1, :]), "L", TEST_IMAGE_SIZE)72 size = (TEST_IMAGE_SIZE[0], TEST_IMAGE_SIZE[1], 5)73 a = numpy.ones(size, dtype=numpy.uint8)74 assert_image(Image.fromarray(a[:, :, 1]), "L", TEST_IMAGE_SIZE)75def test_1d_array():76 a = numpy.ones(5, dtype=numpy.uint8)77 assert_image(Image.fromarray(a), "L", (1, 5))78def _test_img_equals_nparray(img, np):79 assert len(np.shape) >= 280 np_size = np.shape[1], np.shape[0]81 assert img.size == np_size82 px = img.load()83 for x in range(0, img.size[0], int(img.size[0] / 10)):84 for y in range(0, img.size[1], int(img.size[1] / 10)):85 assert_deep_equal(px[x, y], np[y, x])86def test_16bit():87 with Image.open("Tests/images/16bit.cropped.tif") as img:88 np_img = numpy.array(img)89 _test_img_equals_nparray(img, np_img)90 assert np_img.dtype == numpy.dtype("<u2")91def test_1bit():...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run toolium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful