def test_rotated_shape(self): # Compare images with different shapes / rotated. img1 = read(self._test_file('test_image_0.jpg')) img5 = read(self._test_file('test_image_3.jpg')) # rotated with self.assertRaises(ValueError): img1.metrics.mse(img5)
def test_shrunk_shape(self): # Compare images with different shapes / shrunk. img1 = read(self._test_file('test_image_0.jpg')) img4 = read(self._test_file('test_image_2.jpg')) # shrunk with self.assertRaises(ValueError): img1.metrics.mse(img4)
def test_valid_path(self): # Test writing a valid image image = read(self._test_file('test_read_image.jpg')) with self._temp_dir() as temp_dir: path = os.path.join(temp_dir, 'test_write_image.png') write(path, image) self.assertTrue(os.path.exists(path)) new_image = read(path) numpy.testing.assert_array_equal(new_image, image)
def test_cyrillic_path(self): # Test cyrillic filename image = read(self._test_file('test_read_image.jpg')) with self._temp_dir() as temp_dir: path = os.path.join(temp_dir, 'изображения', 'изображение.png') write(path, image) self.assertTrue(os.path.exists(path)) new_image = read(path) numpy.testing.assert_array_equal(new_image, image)
def test_invalid_ext(self): # Test writing a valid image with improper file extension image = read(self._test_file('test_read_image.jpg')) with self._temp_dir() as temp_dir: path = os.path.join(temp_dir, 'foo.xxx') with self.assertRaises(cv2.error): write(path, image)
def test_rect_green(self): img = Image.create(size=self.SIZE) rect = img.draw.rectangle(self.RECT_POINT1, self.RECT_POINT2, color=self.GREEN) expected = read(self._test_file('test_draw_rect_green.png')) numpy.testing.assert_array_equal(rect, expected)
def test_rectangle(self): img = read(self._test_file('test_rect_black.png')) contours = TestElement().find_contours(img, pallet.GRAY) ref_rectangles = [(50, 50, 101, 101)] for i in range(len(contours)): self.assertTrue(contours[i].rectangle, ref_rectangles[i])
def test_roi(self): path = self._test_file(TEST_CASES['test_roi']) img = read(path) roi = img.set_roi(img.width / 2, img.height / 2) offset = roi.width, roi.height contours = TestElement().find_contours(roi, WHITE, offset=offset) img = img.draw.contours(contours, color=GREEN) write(self.get_path(path), img)
def test_rect_thick(self): img = Image.create(size=self.SIZE) rect = img.draw.rectangle(self.RECT_POINT1, self.RECT_POINT2, color=self.WHITE, thickness=5) expected = read(self._test_file('test_draw_rect_thick.png')) numpy.testing.assert_array_equal(rect, expected)
def test_detect(self): img = image.read(self._test_file('telenote', 'test_telenote_00.png')) elements = self.element.detect(img, k=(0.5, 0.5), kernel=5) for element in elements: img = img.draw.contours(element, color=GREEN) img.show()
def test_to_greyscale(self): rgb = read(self._test_file('test_rgb.png')) grey = rgb.mode.to_greyscale() self.assertEqual(rgb.channels, 3) self.assertEqual(grey.channels, 0) # ожидаемая картинка размером 100*100 и с одним планом # левая половина заполнена 91, а правая 123 expected = numpy.full((100, 100), [91] * 50 + [123] * 50) numpy.testing.assert_array_equal(grey, expected)
def test_region(self): # Smooth region img = read(self._test_file('test_smooth.png')) w, h, = img.width, img.height region = (int(w / 2 - w / 4), int(h / 2 - h / 4)), (int(w / 2 + w / 4), int(h / 2 + h / 4)) smoothed = img.filter.blur.gaussian(kernel_size=(99, 99), sigma_x=0, region=region) self.assertAlmostEqual(img.metrics.mse(smoothed), 1215.21, delta=0.01)
def generate_scene(args): """Returns a pixel function for the specified scene.""" if args.picpat == "pic": img = image.read(args.infile).scale(args.scale) if (args.tile): scene = image.tile(img) else: scene = image.center(img, image.mattes[args.matte]) else: # "pat" subcommand size = args.pattern_size * args.scale scene = patterns.fetch_pattern(args.pattern, args.pixtype, size) return scene
def test_rect_ranged(self): _ = [0, 25, 75] k_range = [(i / 100, j / 100) for i in _ for j in _] test_case_path = TEST_CASES['rect_ranged'] for k in k_range: img = read(test_case_path) contours = TestElement().find_contours(img, GRAY, k) img = img.draw.contours(contours, color=(0, 255, 0)) path = self.get_path(test_case_path) dir_name = dirname(path) base_name = basename(path) file_name, extension = splitext(base_name) file_name = f'{file_name}_{str(int(k[0]*100)).zfill(2)}_{str(int(k[1]*100)).zfill(2)}{extension}' write(join(dir_name, file_name), img)
def compress_jpeg(image, qf): """ :param image: input image :type image: PIL.Image :param qf: quality factor of the new .jpeg output :type qf: int (1~95) :return: the modified image :rtype: PIL.Image """ TMP_PATH = './tmp.jpg' image.save(TMP_PATH, 'jpeg', quality=qf) out = read(TMP_PATH) remove(TMP_PATH) return out
def preprocess(self, request): """ Decode all input images into numpy array. Note: This implementation doesn't properly handle error cases in batch mode, If one of the input images is corrupted, all requests in the batch will fail. :param request: :return: """ img_list = [] param_name = self.signature['inputs'][0]['data_name'] input_shape = self.signature['inputs'][0]['data_shape'] for idx, data in enumerate(request): img = data.get(param_name) if img is None: img = data.get("body") if img is None: img = data.get("data") if img is None or len(img) == 0: self.error = "Empty image input" return None # We are assuming input shape is NHWC [h, w] = input_shape[1:3] try: img_arr = image.read(img) except Exception as e: logging.warn(e, exc_info=True) self.error = "Corrupted image input" return None img_arr = image.resize(img_arr, w, h) img_arr = image.transform_shape(img_arr) img_list.append(img_arr) #Convert to dict before returning [{name: image}] img_list = [{param_name: img} for img in img_list] return img_list
def test_smooth(self): # Smooth entire image img = read(self._test_file('test_smooth.png')) smoothed = img.filter.blur.gaussian(kernel_size=(99, 99), sigma_x=0) self.assertAlmostEqual(img.metrics.mse(smoothed), 2326.74, delta=0.01)
import matplotlib.pyplot as plt import numpy as np import cv2 import transform, image img1 = image.read('book1.jpg') img2 = image.read('book2.jpg') points1, features1 = image.orb_features(image.to_grayscale(img1), length=1000) points2, features2 = image.orb_features(image.to_grayscale(img2), length=1000) ''' plt.subplot(1,2,1) plt.imshow(cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)) plt.scatter([point.pt[0] for point in points1], [point.pt[1] for point in points1], c='r', s=40) plt.subplot(1,2,2) plt.imshow(cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)) plt.scatter([point.pt[0] for point in points2], [point.pt[1] for point in points2], c='r', s=40) plt.show() ''' #T, points1, points2, votes = transform.ransac(points1, features1, points2, features2) #T = transform.change_axis_system(T) matches = image.match(features1, features2) plt.subplot(1, 2, 1) plt.imshow(cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)) plt.scatter([points1[m[0]].pt[0] for m in matches], [points1[m[0]].pt[1] for m in matches],
def test_size(self): img3 = read(self._test_file('test_rgb.png')) self.assertEqual(img3.size, img3.width * img3.height * img3.channels)
count = np.count_nonzero(fgmask) print('Frame: %d, Pixel Count: %d' % (frameCount, count)) if (frameCount > 1 and count > 5000): print('Sufficient Motion Detected') cv2.putText(resizedFrame, 'Detected', (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA) if time_ <= 0: img_name = "opencv_frame_{}.png".format(img_counter) cv2.imwrite(img_name, frame) #imgArr = base64.b64encode(np.array(PIL.Image.open(img_name)))) with open(img_name, "rb") as image: f = image.read() b = bytearray(f) encoded_string = base64.b64encode(b) #url = 'http://92.38.176.13/motion.php' myobj = {'IMAGE': encoded_string} x = requests.post(url, data=myobj) print("{} written!".format(img_name)) os.unlink(img_name) img_counter += 1 time_ = 1200 if not videoSent: videoCap() videoSent = True cv2.imshow('Frame', resizedFrame) cv2.moveWindow('Frame', 600, 240)
def test_valid_path(self): # Test a valid image path test_file_name = self._test_file('test_read_image.jpg') self.assertTrue(read(test_file_name).size == self.ref_size)
def test_cyrillic_path(self): # Test cyrillic filename test_file_name = self._test_file('изображения', 'изображение.jpg') self.assertTrue(read(test_file_name).size == self.ref_size)
def test_invalid_path(self): # Test an invalid image path test_file_name = self._test_file('foo.jpg') with self.assertRaises(FileNotFoundError): read(test_file_name)
def test_channels(self): img1 = read(self._test_file('test_image_0.jpg')) img2 = read(self._test_file('test_greyscale.png')) self.assertEqual(img1.channels, 3) self.assertEqual(img2.channels, 3)
if min_error < error: centers[cid] = candidates[min_index] else: centers = old_centers assignments = [d[centers].argmin() for d in D] clusters = [[i for i, c in enumerate(assignments) if c == cid] for cid in range(k)] return clusters k = int(sys.argv[1]) image_dir = sys.argv[2] filenames = sorted(os.listdir(image_dir)) images = [ image.read(path.join(image_dir, filename)) for filename in filenames ] gray = [ image.to_grayscale(img) for img in images ] results = [ image.orb_features(img) for img in gray ] keypoints, features = zip(*results)
def loadImage(self, imagePath): img = image.read(imagePath) self.image['width'] = img[0] self.image['height'] = img[1] self.image['data'] = img[2]
def test_width(self): img1 = read(self._test_file('test_image_0.jpg')) self.assertEqual(img1.width, 1511)
def image(index): if index < 0: return flask.make_response('index cannot be negative', 404) if index >= len(app.config['annotations'].keys()): return flask.make_response('index cannot be larger than amount of images', 404) image = sorted(app.config['annotations'].keys())[index] image = img.read(image) image = img.convert_color_space( image, source_color_space=app.config['arguments']['color_space'], target_color_space='RGB', ) if 'crop' in flask.request.args: try: center_x = float(flask.request.args['centerX']) center_y = float(flask.request.args['centerY']) radius = float(flask.request.args['radius']) except (KeyError, ValueError): return flask.make_response('centerX, centerY, or radius missing or malformed', 404) upper_left = np.array([[center_x - radius], [center_y - radius]]) lower_right = np.array([[center_x + radius], [center_y + radius]]) image = img.crop( image, upper_left, lower_right, [ app.config['arguments']['default_gray'], app.config['arguments']['default_gray'], app.config['arguments']['default_gray'], ], ) if 'scale' in flask.request.args: try: scale_width = int( flask.request.args['width']) if 'width' in flask.request.args else None scale_height = int( flask.request.args['height']) if 'height' in flask.request.args else None except ValueError: return flask.make_response('width or height malformed', 404) if scale_width is None and scale_height is None: return flask.make_response('width and height missing', 404) if scale_width is None: scale_width = int(scale_height / image.shape[0] * image.shape[1]) if scale_height is None: scale_height = int(scale_width / image.shape[1] * image.shape[0]) size = np.array([[scale_width], [scale_height]]) image = img.resize(image, size) response = flask.make_response(img.encode(image, 'png')) response.headers['Content-Type'] = 'image/png' return response
def test_height(self): img1 = read(self._test_file('test_image_0.jpg')) self.assertEqual(img1.height, 2015)
# Remove caching mechanism to recompute left and right disparities import os import pickle if len(sys.argv) <= 2: print("Requires left and right image path as input!") exit() L_path = sys.argv[1] R_path = sys.argv[2] L_disparity_map_path = L_path + ".map" R_disparity_map_path = R_path + ".map" L = image.read(L_path) R = image.read(R_path) L = image.as_greyscale(L) R = image.as_greyscale(R) # Crop excess height height = numpy.min([L.shape[0], R.shape[0]]) width = numpy.min([L.shape[1], R.shape[1]]) L = L[:height, :width] R = R[:height, :width] # Scale by height
#numpy.random.seed(382) skip = False if (sys.argv[1] == "skip"): skip = True ##### Growing Correspondence Seeds if skip == False: L_path = sys.argv[1] R_path = sys.argv[2] L_image = image.greyscale(image.read(L_path, scale = SCALE)) R_image = image.greyscale(image.read(R_path, scale = SCALE)) if (L_image.shape[0] != R_image.shape[0]): print("Left and Right image shapes differ!") exit() (height, width) = shape = L_image.shape # Preemptive Matching... Randomize dd_range = numpy.array(range(DISPARITY_SPAN))-DISPARITY auxilary = numpy.nan*numpy.ones([height, width, DISPARITY_SPAN]) Seeds_count = int(2*numpy.sqrt(width*height))