def add_vhs_color_distortion(img, spacing=5): """Adds blue and red image copies, shifted to the left and right. spacing: How much the copies are shifted, in pixels. """ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Create blue and red parts using HSV - blue is NOT full RGB/BGR blue sat = np.full(gray.shape, 100, dtype="uint8") blue_hue = np.full(gray.shape, 180 // 2, dtype="uint8") # opencv uses 0-179 for hue red_hue = np.full(gray.shape, 0, dtype="uint8") # The value part of HSV is from the grayscale image blue = cv2.merge(np.array([blue_hue, sat, gray], dtype="uint8")) red = cv2.merge(np.array([red_hue, sat, gray], dtype="uint8")) # Convert blue = cv2.cvtColor(blue, cv2.COLOR_HSV2BGR) red = cv2.cvtColor(red, cv2.COLOR_HSV2BGR) # Shift them over blue = imutils.translate(blue, spacing, 0) # Left red = imutils.translate(red, -spacing, 0) # Right # Add them on top, using "lighten only" - only higher value pixels show up np.copyto(img, blue, where=(blue > img)) np.copyto(img, red, where=(red > img)) # Increase saturation and value result_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV).astype("float32") h, s, v = cv2.split(result_hsv) s *= 1.5 # Add saturation s = np.clip(s, 0, 255) v += 20 # Brighten image v = np.clip(v, 0, 255) result_hsv = cv2.merge([h, s, v]) result = cv2.cvtColor(result_hsv.astype("uint8"), cv2.COLOR_HSV2BGR) return result
def random_translation(img, label, attention): # t = [(0, 5), (5, 0), (-5, 0), (0, -5)] # idx = np.random.randint(0, len(t)) # return translate(img, t[idx][0], t[idx][1]), translate(label, t[idx][0], t[idx][1]), \ # translate(attention, t[idx][0], t[idx][1]) x = np.random.randint(-5, 5, size=1) y = np.random.randint(-5, 5, size=1) return translate(img, x, y), translate(label, x, y), translate(attention, x, y)
def _compute_cost_paper_mode(self): """ Compute the cost of a given img, as in the paper, except we used auto-canny for the binary edge detection part. """ wz, wd, wg = 0.43, 0.43, 0.14 fz = np.zeros((*self.img.shape[:2], 8)) fd = np.zeros((*self.img.shape[:2], 8)) fg = np.zeros((*self.img.shape[:2], 8)) translator = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)] ez = (255 - self.edges) / 255 for i, t in enumerate(translator): fz[:, :, i] = imutils.translate(ez, *t) grayscale_img = cv2.cvtColor(self.img, cv2.COLOR_RGB2GRAY) Ix = (imutils.translate(grayscale_img, -1, 0) - grayscale_img).astype('float64') Iy = (imutils.translate(grayscale_img, 0, -1) - grayscale_img).astype('float64') G = np.sqrt(np.square(Ix) + np.square(Iy)) eg = 1 - G / np.max(G) for i, t in enumerate(translator): fg[:, :, i] = imutils.translate(eg, *t) if i % 2 == 0: fg[:, :, i] = fg[:, :, i] / np.sqrt(2) Dp = np.zeros((*self.img.shape[:2], 2)) Dp[:, :, 0] = np.where(G > 0, Iy / G, Iy) Dp[:, :, 1] = np.where(G > 0, -Ix / G, -Ix) dp = np.zeros((*self.img.shape[:2], 8)) dq = np.zeros((*self.img.shape[:2], 8)) for i, t in enumerate(translator): tile = np.tile( -np.array(t), (*self.img.shape[:2], 1)) / (np.sqrt(2) if i % 2 == 1 else 1) conds = np.zeros((*self.img.shape[:2], 2)) conds[:, :, 0] = np.tensordot(Dp, -np.array(t), axes=(2, 0)) >= 0 conds[:, :, 1] = np.tensordot(Dp, -np.array(t), axes=(2, 0)) >= 0 L = np.where(conds, tile, -tile) dp[:, :, i] = np.sum(Dp * L, axis=2) dq[:, :, i] = np.sum(imutils.translate(Dp, *t) * L, axis=2) # There is a mistake in the paper, the max possible value of the sum of these 2 arccos is 1.5*pi, not pi. # So to make sure a max possible path cost of 1, we divide the thing by 1.5*pi instead. fd = 1 / (1.5 * np.pi) * (np.arccos(dp) + np.arccos(dq)) return wz * fz + wd * fd + wg * fg
def main(): if Carl: runLog.logger.info("Started") egpg = easygopigo3.EasyGoPiGo3(use_mutex=True) if Carl: tiltpan.tiltpan_center() sleep(0.5) tiltpan.off() try: image = cv2.imread(args["image"]) cv2.imshow("Original", image) M = np.float32([[1, 0, 25], [0, 1, 50]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted Down and Right", shifted) M = np.float32([[1, 0, -50], [0, 1, -90]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted Up and Left", shifted) shifted = imutils.translate(image, 0, 100) cv2.imshow("imutils.translate() Down 100", shifted) cv2.waitKey(0) except KeyboardInterrupt: # except the program gets interrupted by Ctrl+C on the keyboard. if (egpg != None): egpg.stop() # stop motors print("\n*** Ctrl-C detected - Finishing up") sleep(1) if (egpg != None): egpg.stop() if Carl: runLog.logger.info("Finished") sleep(1)
def center_extent(image, size): (eW, eH) = size if image.shape[1] > image.shape[0]: image = imutils.resize(image, width=eW) else: image = imutils.resize(image, height=eH) extent = np.zeros((eH, eW), dtype="uint8") offsetX = (eW - image.shape[1]) // 2 offsetY = (eH - image.shape[0]) // 2 extent[offsetY:offsetY + image.shape[0], offsetX:offsetX + image.shape[1]] = image #try to visualize what's happening, its simple CM = mahotas.center_of_mass( extent) #weighted mean of white pixels in image (cY, cX) = np.round(CM).astype("int32") (dX, dY) = ((size[0] // 2) - cX, (size[1] // 2) - cY) #M = np.float32([[1, 0, dX], [0, 1, dY]]) #extent = cv2.warpAffine(extent, M, size) extent = imutils.translate(extent, dX, dY) #the above two lines are nothing but translation return extent
def translationOp(self): # read image im = cv2.imread(self.Image) # NOTE: Translating (shifting) an image is given by a NumPy matrix in # the form: # [[1, 0, shiftX], [0, 1, shiftY]] # You simply need to specify how many pixels you want to shift the image # in the X and Y direction -- let's translate the image 25 pixels to the # right and 50 pixels down M = np.float32([[1, 0, 25], [0, 1, 50]]) shifted = cv2.warpAffine(im, M, (im.shape[1], im.shape[0])) # show shifted image and wait for key press cv2.imshow("Image", shifted) cv2.waitKey(0) # now, let's shift the image 50 pixels to the left and 90 pixels up, we # accomplish this using negative values M = np.float32([[1, 0, -50], [0, 1, -90]]) shifted = cv2.warpAffine(im, M, (im.shape[1], im.shape[0])) cv2.imshow("Shifted Up and Left", shifted) cv2.waitKey(0) # shift down shifted = imutils.translate(im, 0, 100) cv2.imshow("shifted down", shifted) cv2.waitKey(0) return
def img_loader(image_list): batch_img_list = [] for i in image_list: input = cv2.imread(i) flip_ran = random.randint(0, 3) if flip_ran == 0: input = cv2.flip(input, 0) elif flip_ran == 1: input = cv2.flip(input, 1) elif flip_ran == 2: input = cv2.flip(input, 1) input = cv2.flip(input, 0) rotate_v = random.randint(-30, 30) # TODO : 이미지에서 몇 펴센트 shift()를 진행할지를 결정. # TODO : 얼마나 움직이는지는 이중 랜덤으로 결정해야한다. shift_y = input.shape[0] * 0.1 random_y = random.randint(-shift_y, shift_y) shift_x = input.shape[1] * 0.1 random_x = random.randint(-shift_x, shift_x) input = imutils.translate(input, random_x, random_y) input = imutils.rotate(input, rotate_v) # 모델과 데이터 수 , 전처리 + 이미지를 어떻게 집어넣느냐가 모델 정확성에 정말 많은 부분을 차지한다. input = cv2.resize(input, (56, 56)) # hyper parameter >> 어떤 데이터에서 어떤 모델은 어떨때 가장 좋은지를 계속 피드백. batch_img_list.append(input) # dtype - int 로 하면 error 발생된다. return np.array(batch_img_list, dtype=np.float32)
def img_loader(image_list, train): batch_img_list = [] for i in image_list: input = cv2.imread(i) if (train == 1): flip_ran = random.randint(0, 3) if flip_ran == 0: input = cv2.flip(input, 0) elif flip_ran == 1: input = cv2.flip(input, 1) elif flip_ran == 2: input = cv2.flip(input, 1) input = cv2.flip(input, 0) rotate_v = random.randint(-30, 30) shift_y = input.shape[0] * 0.1 shift_y = math.ceil(shift_y) random_y = random.randint(-shift_y, shift_y) shift_x = input.shape[1] * 0.1 shift_x = math.ceil(shift_x) random_x = random.randint(-shift_x, shift_x) input = imutils.translate(input, random_x, random_y) input = imutils.rotate(input, rotate_v) input = cv2.resize(input, (56, 56)) # hyper parameter >> 어떤 데이터에서 어떤 모델은 어떨때 가장 좋은지를 계속 피드백. batch_img_list.append(input) # dtype - int 로 하면 error 발생된다. return np.array(batch_img_list, dtype=np.float32)
def transform_img(img, w, x, y): ''' rotate by w (degree) first then translate by x, y (pixel) ''' img_rot = imutils.rotate(img.copy(), w) img_tran = imutils.translate(img_rot.copy(), x, y) return img_tran
def translate(self, x: int, y: int): """translate image to given offsets""" self.mat = imutils.translate( image=self.mat, x=x, y=y, ) return self
def transformation(img): negativeImg = 255 - img negativeRotation = imutils.rotate(negativeImg, 15) translateImg = imutils.translate(img, 15, 15) rotateImg = imutils.rotate(img, 15) imgTitle = ['Rotation', 'Translation', 'NegativeImg', 'NegativeRotation'] imgList = [rotateImg, translateImg, negativeImg, negativeRotation] pltImg(4, 4, 4, 13, imgList, imgTitle)
def translate(img, x=0, y=0): if y == 0: y = randrange(-5, 5) # print(y) if x == 0: x = randrange(-5, 5) # print(x) translated = imutils.translate(img, x, y) # show_img(translated, 'translated') return translated
def translate(img, img_id): res = [] res_id = [] res.append( imutils.translate(img, img_size // 2, 0).reshape(img_size, img_size, 1)) res_id.append(img_id) res.append( imutils.translate(img, -(img_size // 2), 0).reshape(img_size, img_size, 1)) res_id.append(img_id) res.append( imutils.translate(img, 0, img_size // 2).reshape(img_size, img_size, 1)) res_id.append(img_id) res.append( imutils.translate(img, 0, -(img_size // 2)).reshape(img_size, img_size, 1)) res_id.append(img_id) return res, res_id
def Piezoresponse(self, phasechannel, ampchannel, fix=False): phaseimg = h5toimg(self.data, phasechannel)[0] ampimg = h5toimg(self.data, ampchannel)[0] piezoresponse = ampimg * np.cos(phaseimg * np.pi / 180) if fix: piezoresponse = imutils.translate(piezoresponse, self.trans[0], self.trans[1]) piezoresponse = imutils.rotate(piezoresponse, self.angle) #self.piezo = piezoresponse.astype(np.uint8) self.piezo = piezoresponse return self.piezo
def switch(t): global text global final_image if t == "translate": x = 50 if not args["shift_x"] else int(args["shift_x"][0]) y = 50 if not args["shift_y"] else int(args["shift_y"][0]) final_image = imutils.translate(final_image, x, y) # cv2.imshow("translated x {} px, y {} px".format(x,y), final_image) text += "translated x {} px, y {} px \n ".format(x, y) if t == "rotate": a = 90 if not args["angle"] else int(args["angle"][0]) c = None if not args["centre"] else tuple(args["centre"]) final_image = imutils.rotate(final_image, a, center=c, scale=1.0) # cv2.imshow("rotated {} degrees, around {}, scaled {}".format(a,c,1.0), final_image) text += "rotated {} degrees, around {}, scaled {} \n ".format( a, c, 1.0) if t == "resize": hr = float(args["height_ratio"][0]) wr = float(args["width_ratio"][0]) (oh, ow) = final_image.shape[:2] nh = int(hr * oh) nw = int(wr * ow) final_image = imutils.resize(final_image, width=nw, height=nh) # cv2.imshow("resized {} px height, {} px width".format(nh, nw), final_image) text += "resized {} px height, {} px width ".format(nh, nw) if t == "flip": d = int(args["flip_direction"][0]) sfd = "horizontally" if d == 1 else "vertically" sfd = "both horizontally, and vertically" if d == -1 else sfd final_image = cv2.flip(final_image, d) text += "flipped {}".format(sfd) if t == "crop": crop_area = args["crop_area"][0] final_image = image[0:int(image.shape[0] / 2), 0:int(image.shape[1] / 2)] if crop_area == "tl" else final_image final_image = image[:-int(image.shape[0] / 2), -int(image.shape[1] / 2):] if crop_area == "tr" else final_image final_image = image[ -int(image.shape[0] / 2):, :-int(image.shape[1] / 2)] if crop_area == "bl" else final_image final_image = image[-int(image.shape[0] / 2):, -int(image.shape[1] / 2):] if crop_area == "br" else final_image final_image = image[ int(image.shape[0] / 4):-int(image.shape[0] / 4), int(image.shape[1] / 4):-int(image.shape[1] / 4)] if crop_area == "cr" else final_image text += "cropped area: {}".format(crop_area)
def overlay_imgs(beforeimg, afterimg, T): shift1 = T[0, 2] shift2 = T[1, 2] rot = np.arccos(T[0, 0]) translated = imutils.translate(beforeimg, shift1, shift2) print(translated.shape) translated[:, :, 0:2] = 0 afterimg[:, :, 0] = 0 afterimg[:, :, 2] = 0 v = cv2.addWeighted(translated, 0.5, afterimg, 0.5, 0) cv2.imwrite('play.jpg', v) cv2.imshow("window", v) cv2.waitKey(0)
def __init__(self, root, im_file, mask_dir): self._reader = ImageReader(root, im_file, mask_dir) self._img = self._reader.image self._orig_mask = self._reader.mask self._scale = np.float32(self._orig_mask.shape) / 540. self._scale[0], self._scale[1] = self._scale[1], self._scale[0] self._img = cv2.resize(self._img, (540, 540)) self._mask = cv2.resize(self._orig_mask, (540, 540)) self._shifted = cv2.bitwise_and(translate(self._mask, 40, 30), translate(self._mask, -40, -30)) self._img [self._mask == 0] = 0 # get green channel self._green = self._img[:, :, 1].astype('float32') # kick-start processing self._processed = self._green.copy()
def NormPiezoresponse(self, phasechannel, ampchannel, fix=False): phaseimg = h5toimg(self.data, phasechannel)[0] ampimg = h5toimg(self.data, ampchannel)[0] Normpiezo = ampimg * np.cos(phaseimg * np.pi / 180) / np.max(ampimg) #Normpiezo = np.zeros(piezo.shape) #Normpiezo = cv2.normalize(piezo, Normpiezo, 0, 255, cv2.NORM_MINMAX) if fix: Normpiezo = imutils.translate(Normpiezo, self.trans[0], self.trans[1]) Normpiezo = imutils.rotate(Normpiezo, self.angle - 90) self.Normpiezo = Normpiezo #print(np.max(ampimg/np.max(ampimg))) #print(np.min(ampimg/np.max(ampimg))) return self.Normpiezo
def get_hu_moment(let, font=cv2.FONT_ITALIC, scale=15, rotation=0, translation=(0, 0), blur=0): img = np.zeros((height, width, 1), np.uint8) cv2.putText(img, let, img_corner, font, scale, white, thickness) img = imutils.rotate(img, rotation) img = imutils.translate(img, translation[0], translation[1]) if blur > 0: blur = blur * 2 + 1 kernel = np.ones((blur, blur), np.float32) / (blur*blur) img = cv2.filter2D(img, -1, kernel) cv2.namedWindow("img") cv2.imshow("img", img) print("translation: ", translation, "; scale = ", scale, "; rotation= ", rotation, "; blur= ", blur, ";", sep='') cv2.waitKey(0) return cv2.HuMoments(cv2.moments(img)).flatten()
def zoom_image(img): # Initiate roi list/matrix, we only calculate on 2D plane roi = np.float32([[1, 0, 0], [0, 1, 0]]) # Zoom out image # Expand the image to 3000 x 3000 px zoom = cv2.warpAffine(img, roi, (3000, 3000)) # Matching the center point of the original image to the new center point of 3000 x 3000 px image shift_image = imutils.translate(zoom, (1500 - 1920 / 2), (1500 - 1080 / 2)) ### Debug: Show enlarged & shifted image # cv2.imshow("Test image", shift_image) # cv2.waitKey() return shift_image
def Zoom(cv2Object, point, zoomSize): # Resizes the image/video frame to the specified amount of "zoomSize". # A zoomSize of "2", for example, will double the canvas size cv2Object = imutils.resize(cv2Object, width=(zoomSize * cv2Object.shape[1])) # center is simply half of the height & width (y/2,x/2) center = (int(cv2Object.shape[0] / 2), int(cv2Object.shape[1] / 2)) # cropScale represents the top left corner of the cropped frame (y/x) cropScale = (int(center[0] / zoomSize), int(center[1] / zoomSize)) dx = point[0] - center[1] dy = point[1] - center[0] if dx > 0: dx = 0 if dy > 0: dy = 0 scale = zoomSize - 1 scale = scale * -1 if dx < 0: if zoomSize > 1: if (frame_center[1] * scale) > dx: dx = frame_center[1] * scale elif dx != 0: dx = 0 if dy < 0: if zoomSize > 1: if (frame_center[0] * scale) > dy: dy = frame_center[0] * scale elif dy != 0: dy = 0 cv2Object = imutils.translate(cv2Object, dx, dy) # The image/video frame is cropped to the center with a size of the original picture # image[y1:y2,x1:x2] is used to iterate and grab a portion of an image # (y1,x1) is the top left corner and (y2,x1) is the bottom right corner of new cropped frame. cv2Object = cv2Object[0:(center[0] + cropScale[0]), 0:(center[1] + cropScale[1])] cv2Object = imutils.resize(cv2Object, width=width) (h, w) = cv2Object.shape[:2] #print(h, w) return cv2Object
def random_translation(image, horizontal_max=6, vertical_max=6): # Remove the channel. image = np.squeeze(image) # Randomly apply translation to image. horizontal_translation = np.random.randint(-horizontal_max, horizontal_max + 1) vertical_translation = np.random.randint(-vertical_max, vertical_max + 1) translated = imutils.translate(image, horizontal_translation, vertical_translation) # Add the channel. image = np.reshape(translated, (image.shape[0], image.shape[1], 1)) return image
def translate(args): # shift the image 25 pixels to the right and 50 pixels down M = np.float32([[1, 0, 25], [0, 1, 50]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted Down and Right", shifted) # now, let's shift the image 50 pixels to the left and 90 pixels # # up by specifying negative values for the x and y directions, # # respectively M = np.float32([[1, 0, -50], [0, 1, -90]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted Up and Left", shifted) # use the imutils helper function to translate the image 100 pixels # # down in a single function call shifted = imutils.translate(image, 0, 100) cv2.imshow("Shifted Down", shifted) cv2.waitKey(0)
def binary_img(img, trans, angle, cut=False, invert=False): height, width = img.shape if len(img.shape) == 2 else img.shape[:2] #img = (img / (np.max(img) - np.min(img))*256).astype(np.uint8) img = imutils.translate(img, trans[0], trans[1]) img = imutils.rotate(img, angle) if cut: h, w = int(height * (0.5 / np.sqrt(2))), int(width * (0.5 / np.sqrt(2))) img = img[int(height / 2 - h):int(height / 2 + h), int(width / 2 - w):int(width / 2 + w)] if invert: _, img_result = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) else: _, img_result = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) #plt.imsave('test_cov.png', img_result, cmap='gray') #print(np.unique(img_result)) return img_result
def find_offset(beforeimg, afterimg): c1x, c1y, annotated_before = find_centroid(beforeimg, 'BEFORE', (255, 255, 255)) cv2.imwrite('annotated_before.jpg', annotated_before) c2x, c2y, annotated_after = find_centroid(afterimg, 'AFTER', (255, 255, 255)) cv2.imwrite('annotated_after.jpg', annotated_after) dx = c2x - c1x dy = c2y - c1y print(c1x, c1y, c2x, c2y) print(f'offset dx = {dx} , dy={dy}') translated = imutils.translate(annotated_before, dx, dy) translated[:, :, 0:2] = 0 afterimg[:, :, 0] = 0 afterimg[:, :, 2] = 0 v = cv2.addWeighted(translated, 0.5, annotated_after, 0.5, 0) cv2.imwrite('overlay.jpg', v) return (dx, dy)
def img_augmentation(input, flip_ran, rotate_v): if flip_ran == 0: input = cv2.flip(input, 0) elif flip_ran == 1: input = cv2.flip(input, 1) elif flip_ran == 2: input = cv2.flip(input, 1) input = cv2.flip(input, 0) shift_y = input.shape[0] * 0.1 shift_y = math.ceil(shift_y) random_y = random.randint(-shift_y, shift_y) shift_x = input.shape[1] * 0.1 shift_x = math.ceil(shift_x) random_x = random.randint(-shift_x, shift_x) input = imutils.translate(input, random_x, random_y) input = imutils.rotate(input, rotate_v) input = cv2.resize(input, (224, 224)) return input
def _handle_move(self, item, image): offset_x = randrange(self.min_move_offset_x, self.max_move_offset_x) offset_y = randrange(self.min_move_offset_y, self.max_move_offset_y) shifted = imutils.translate(image, offset_x, offset_y) output_file = os.path.join(self.images_directory, random_string() + ".jpg") cv2.imwrite(output_file, shifted) image_element = Image(output_file) for box_item in item.boxes: x, y = box_item.left, box_item.top cx = x + offset_x cy = y + offset_y if cx < 0 or cy < 0: continue x = cx y = cy box = Box() box.left = x box.top = y box.width = box_item.width box.height = box_item.height for part_item in box_item.parts: part = Part() part.x = part_item.x + offset_x part.y = part_item.y + offset_y part.name = part_item.name box.parts.append(part) image_element.boxes.append(box) self.xml_file.append_image(image_element)
def next_batch(self, batch_size): images_batch = np.zeros( (batch_size, self.fine_size, self.fine_size, 1)) labels_batch = np.zeros(batch_size) for i in range(batch_size): label, pixels = self.training_data[self._train_idx] if self.randomize: angle = np.random.random_integers(-30, 30) pixels = imutils.rotate(pixels, angle) translate_x = np.random.random_integers(-3, 3) translate_y = np.random.random_integers(-3, 3) pixels = imutils.translate(pixels, translate_x, translate_y) pixels = pixels.reshape((self.fine_size, self.fine_size, 1)) images_batch[i, ...] = pixels labels_batch[i, ...] = label self._train_idx += 1 if self._train_idx == self.num_train: self._train_idx = 0 return images_batch, labels_batch
#!/usr/bin/env python import numpy as np import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) cv2.waitKey(0) M = np.float32([[1, 0, 25], [0, 1, 50]]) # print(M) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted Down and Right", shifted) cv2.waitKey(0) M = np.float32([[1, 0, -50], [0, 1, -90]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted Up and Left", shifted) cv2.waitKey(0) shifted = imutils.translate(image, 0, 100) cv2.imshow("Shifted Down", shifted) cv2.waitKey(0)
import matplotlib.pyplot as plt import imutils import cv2 # load the example images bridge = cv2.imread("../demo_images/bridge.jpg") cactus = cv2.imread("../demo_images/cactus.jpg") logo = cv2.imread("../demo_images/pyimagesearch_logo.jpg") workspace = cv2.imread("../demo_images/workspace.jpg") # 1. TRANSLATION # show the original image cv2.imshow("Original", workspace) # translate the image x-50 pixels to the left and y=100 pixels down translated = imutils.translate(workspace, -50, 100) cv2.imshow("Translated", translated) cv2.waitKey(0) # translate the image x=25 pixels to the right and y=75 pixels up translated = imutils.translate(workspace, 25, -75) cv2.imshow("Translated", translated) cv2.waitKey(0) cv2.destroyAllWindows() # 2. ROTATION # loop over the angles to rotate the image for angle in range(0, 360, 90): # rotate the image and display it rotated = imutils.rotate(bridge, angle=angle) cv2.imshow("Angle=%d" % (angle), rotated)
image8bit2 = generate_displaced_LG_Mask(beamCharge2, gratingPeriod2) else: image8bit1 = generate_LG_Mask(beamCharge1) image8bit2 = generate_LG_Mask(beamCharge2) if maskRadius > 0: image8bit1 = cv2.bitwise_and(image8bit1, image8bit1 , mask = maskCircle) image8bit2 = cv2.bitwise_and(image8bit2, image8bit2 , mask = maskCircle) else: image8bit1 = cv2.bitwise_and(image8bit1, image8bit1 , mask = maskWindow) image8bit2 = cv2.bitwise_and(image8bit2, image8bit2 , mask = maskWindow) # translate the image x=100 pixels to the left and y=0 pixels up image8bit1 = imutils.translate(image8bit1, -ImgResX/4, 0) image8bit2 = imutils.translate(image8bit2, ImgResX/4, 0) image8bit = cv2.add(image8bit1,image8bit2) # apply SLM correction mask provided by manufacturer if correctionFlag == True: image8bit = apply_correction_mask(image8bit) cv2.imshow('phase hologram',image8bit) cv2.waitKey() if saveFlag == True: scipy.misc.imsave(fileStr, image8bit) print "file: " + fileStr + " saved! Press any key to continue."
import argparse import cv2 # from ex1 import imutils import imutils # python translation.py --image ../../OpenCV_Basic_Exercises/images/image1.jpg ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True) args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) shifted = imutils.translate(image, 25, 50) cv2.imshow("Shifted Down and Right", shifted) shifted_up_and_left = imutils.translate(image, -50, -90) cv2.imshow("Shifted Up and Left", shifted_up_and_left) shifted_down = imutils.translate(image, 0, 100) cv2.imshow("Shifted Down", shifted_down) cv2.waitKey(0)
def shiftedUp20(data): translated = imutils.translate(data, 0, -5) translated2 = translated.reshape(2304).tolist() return translated2
import imutils import cv2 # configure argument parser # path to image only argument ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) cv2.waitKey(0) # translate image shifted = imutils.translate(image, 25, 50) cv2.imshow("Shifted Down and Right", shifted) shifted = imutils.translate(image, -50, -90) cv2.imshow("Shifted Up and Left", shifted) shifted = imutils.translate(image, 0, 100) cv2.imshow("Shifted Down", shifted) cv2.waitKey(0) # print "image ratio is: %d / %d = %f" % (150, image.shape[1], r) # print r # resize width resized = imutils.resize(image,width=150) cv2.imshow("Resized (Width)", resized)
def shiftedRight20(data): translated = imutils.translate(data, 5, 0) translated2 = translated.reshape(2304).tolist() return translated2
ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) # Load the image and show it image = cv2.imread(args["image"]) cv2.imshow("Original", image) # NOTE: Translating (shifting) an image is given by a # NumPy matrix in the form: # [[1, 0, shiftX], [0, 1, shiftY]] # You simply need to specify how many pixels you want # to shift the image in the X and Y direction. # Let's translate the image 25 pixels to the right and # 50 pixels down M = np.float32([[1, 0, 25], [0, 1, 50]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted Down and Right", shifted) # Now, let's shift the image 50 pixels to the left and # 90 pixels up. We accomplish this using negative values M = np.float32([[1, 0, -50], [0, 1, -90]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted Up and Left", shifted) # Finally, let's use our helper function in imutils.py to # shift the image down 100 pixels shifted = imutils.translate(image, 0, 100) cv2.imshow("Shifted Down", shifted) cv2.waitKey(0)
#translation.py import numpy as np import argparse import imutils as iu import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) M = np.float32([[1,0,25], [0,1,50]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted down and right", shifted) M = np.float32([[1,0,-50], [0,1,-90]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) cv2.imshow("Shifted up and left", shifted) shifted = iu.translate(image, 0, 100) cv2.imshow("Shifted down", shifted) cv2.waitKey(0)
import numpy as np import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) cv2.waitKey(0) shifted = imutils.translate(image, 25, 50) # cv2.imshow('Shifted Down and Right', shifted) # cv2.waitKey(0) shifted = imutils.translate(image, -25, -50) # cv2.imshow('Shifted Up and Left', shifted) # cv2.waitKey(0) rotated = imutils.rotate(image, 45) # cv2.imshow('Rotated 45 degree', rotated) # cv2.waitKey(0) resized = imutils.resize(image, height=150) # cv2.imshow('Resized to height 150', resized) # cv2.waitKey(0) flipped = cv2.flip(image, 1) # cv2.imshow('Flipped Horizontally', flipped)
import numpy as np import argparse import cv2 import imutils # <~ some helpful functions we wrote ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) # M1 = np.float32([[1, 0, 25], [0, 1, 50]]) # shifted_down = cv2.warpAffine(image, M1, (image.shape[1], image.shape[0])) # cv2.imshow("Shifted Down and Right", shifted_down) # cv2.waitKey(0) # M2 = np.float32([[1, 0, -50], [0, 1, -90]]) # shifted_up = cv2.warpAffine(image, M2, (image.shape[1], image.shape[0])) # cv2.imshow("Shifted Up and Left", shifted_up) # cv2.waitKey(0) shifted_down = imutils.translate(image, 25, 50) cv2.imshow("Shifted Down and Right", shifted_down) cv2.waitKey(0) shifted_up = imutils.translate(image, -50, -90) cv2.imshow("Shifted Up and Left", shifted_up) cv2.waitKey(0)