def test_seam_carving(): img = np.array([[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0]], dtype=np.float) energy = 1 - img out = transform.seam_carve(img, energy, 'vertical', 1, border=0) testing.assert_allclose(out, 0) img = img.T out = transform.seam_carve(img, energy, 'horizontal', 1, border=0) testing.assert_allclose(out, 0)
def seam_carve(image, target_width, target_height, energy_map=filters.sobel_energy_l1): '''Converts an image into target width and height by using seam carving :param image: Input image to be reduced to target width and height :type image: array_like :param target_width: target width of image :type target_width: int :param target_height: target height of image :type target_height: int :param energy_map: A function used to construct the energy matrix for the image :type energy_map: function :return: Seam carved image in which vertical and horizontal seams have been identified and removed to meet the target image size. :rtype: ndarray ''' src_height, src_width = image.shape[:2] t_height = int(float(src_height) * target_width / src_width) if t_height > target_height: logging.info('Reducing image size to %d x %d', target_width, t_height) # Let's do a first level resizing image = vision.resize_by_width(image, target_width) src_height, src_width = image.shape[:2] t_width = int(float(src_width) * target_height / src_height) if t_width > target_width: logging.info('Reducing image size to %d x %d', t_width, target_height) image = vision.resize_by_height(image, target_height) src_height, src_width = image.shape[:2] if target_width < src_width: # compute the energy matrix for the image energy_matrix = energy_map(image) # We need to remove some vertical seams num_seams_to_remove = src_width - target_width logging.info('Removing %d vertical seams', num_seams_to_remove) image = transform.seam_carve(image, energy_matrix, 'vertical', num_seams_to_remove) image = (image * 255).astype('uint8') if target_height < src_height: # compute the energy matrix for the image energy_matrix = energy_map(image) # We need to remove some horizontal seams num_seams_to_remove = src_height - target_height logging.info('Removing %d horizontal seams', num_seams_to_remove) image = transform.seam_carve(image, energy_matrix, 'horizontal', num_seams_to_remove) image = (image * 255).astype('uint8') return image
def work_work_progress(img, remove_direction, num_of_seam_to_delete, algo_type): # Perform seam carving without save option # don't save image if progress button is click, just show it, because if save, a lot of image will be save. import cv2 from skimage import transform from algo import my_algorithm direction = remove_direction # vertical/horizontal seams_per_iter = num_of_seam_to_delete # number of pixels to remove each iteration cv2.imshow('Original Image', img) # # images resizing # print(img.shape) # size_change = img.shape # size_change = [int(x * 1) for x in size_change] # img = cv2.resize(img, (size_change[1], size_change[0])) # print(img.shape) energy_map = my_algorithm(img, algo_type) # put images into a array buffer_image = [] for i in range(0, seams_per_iter): image_result = transform.seam_carve(img, energy_map, direction, i) buffer_image.append(image_result) # Show images only when the steps can be divided by 10 for i in range(0, len(buffer_image)): current_progress = str(i) if i % 10 == 0: cv2.imshow("Result " + current_progress, buffer_image[i])
def carveImg(tImag, tType): if os.path.exists(tImag) is False: print(u"%s not found" % tImag) return # load the image and convert it to grayscale image = cv2.imread(tImag) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # compute the Sobel gradient magnitude representation # of the image -- this will serve as our "energy map" # input to the seam carving algorithm lTemp = filters.sobel(gray.astype("float")) # show the original image cv2.imshow("Original", image) cv2.imshow("temp", lTemp) # loop over a number of seams to remove for numSeams in range(10, 140, 5): # perform seam carving, removing the desired number # of frames from the image -- `vertical` cuts will # change the image width while `horizontal` cuts will # change the image height carved = transform.seam_carve(image, lTemp, tType, numSeams) print("[INFO] removing {} seams; new size: " "w={}, h={}".format(numSeams, carved.shape[1], carved.shape[0])) # show the output of the seam carving algorithm cv2.imshow("Carved", carved) cv2.waitKey(0)
def updatePhoto(e, direction, arrow): global xSeams global ySeams global mag global root global panel global image vh = "" seam = 0 if direction == "x": if arrow == "left": xSeams += 2 if arrow == "right": xSeams -= 2 vh = "vertical" seam = xSeams if direction == "y": if arrow == "up": ySeams += 2 if arrow == "down": ySeams -= 2 vh = "horizontal" seam = ySeams carved = transform.seam_carve(image, mag, vh, seam) b, g, r = cv2.split(carved * 255) carved_image = cv2.merge((r, g, b)) display_image = Image.fromarray(carved_image.astype("uint8")) display_image_actual = ImageTk.PhotoImage(image=display_image) panel.config(image=display_image_actual) panel.image = display_image_actual
def image_resize(request): json_data = json.loads(request.body.decode('utf-8')) width = abs(json_data['width']) height = abs(json_data['height']) img = json_data['image'] ext = img.split('.')[-1] if request.user.is_authenticated: username = request.user.username query = ( Media.objects.filter(owner__username=username).filter(image=img) | Media.objects.filter(image=img).filter(public=True)).first() print(query.width, width, query.height, height) if query.width - width < 0 or query.height - height < 0: return JsonResponse({"error": "Invalid height and width"}) if query is not None: imgpath = os.path.join(settings.MEDIA_ROOT, img) image = Image.open(imgpath) np_img = np.array(image) np_img = util.img_as_float(np_img) eimg = filters.sobel(color.rgb2gray(np_img)) out = transform.seam_carve(np_img, eimg, 'horizontal', query.height - height) out = out / out.max() out = out * 255 eimg = filters.sobel(color.rgb2gray(out)) out = transform.seam_carve(out, eimg, 'vertical', query.width - width) out = out / out.max() out = out * 255 out = out.astype(np.uint8) image = Image.fromarray(out) image = image.resize((width, height), PIL.Image.ANTIALIAS) output = BytesIO() image.save(output, 'JPEG') filecontent = ContentFile(output.getvalue()) media = Media() media.owner = request.user media.dislay_name = query.display_name + ' Resized' media.public = query.public media.image.save('image.jpg', File(filecontent), save=True) return JsonResponse({'link': media.get_link()}) else: raise Http404 else: return redirect('/login?next=/upload')
def image_remove(request): json_data = json.loads(request.body.decode('utf-8')) # width = abs(json_data['width']) # height = abs(json_data['height']) img = json_data['image'] points = json_data['points'] print(points) if request.user.is_authenticated: username = request.user.username query = ( Media.objects.filter(owner__username=username).filter(image=img) | Media.objects.filter(public=True)).first() if query is not None: imgpath = os.path.join(settings.MEDIA_ROOT, img) image = Image.open(imgpath) np_img = np.array(image) np_img = util.img_as_float(np_img) poly = [] xmax = points[0]['x'] xmin = points[0]['x'] for point in points: xmax = max(xmax, point['y']) xmin = min(xmin, point['y']) poly.append((point['y'], point['x'])) pr = np.array([p[0] for p in poly]) pc = np.array([p[1] for p in poly]) rr, cc = draw.polygon(pr, pc) ext = img.split('.')[-1] eimg = filters.sobel(color.rgb2gray(np_img)) print(eimg.shape) print(rr.max(), rr.min(), cc) eimg[rr, cc] -= 1000 out = transform.seam_carve(np_img, eimg, 'vertical', (xmax - xmin) // 3) * 255 out = out.astype(np.uint8) image = Image.fromarray(out) # image = image.resize((width, height), PIL.Image.ANTIALIAS) output = BytesIO() image.save(output, 'BMP') filecontent = ContentFile(output.getvalue()) media = Media() media.owner = request.user media.dislay_name = query.display_name + ' Resized' media.public = query.public media.image.save('image.jpg', File(filecontent), save=True) return JsonResponse({'link': media.get_link()}) else: raise Http404 else: return redirect('/login?next=/upload')
def removeSeam(vid_array, dir, mag): F, H, W, _ = vid_array.shape newH = H - 1 if (dir == 'horizontal') else H newW = W - 1 if (dir == 'vertical') else W new_vid_array = np.zeros((F, newH, newW, 3)).astype(np.uint8) for frame in range(F): new_frame = transform.seam_carve(vid_array[frame], mag, dir, 1) * 255.0 new_vid_array[frame] = new_frame.astype(np.uint8) return new_vid_array.astype(np.uint8)
def carve_image(img, size = 480, target_size = 720): width, height = img.shape[1], img.shape[0] direction = 'vertical' rotate = False if width < height: rotate = True img = imutils.rotate_bound(img, 90) if height > size: img = cv2.resize(img, None, fx=size/height, fy=size/height, interpolation=cv2.INTER_AREA) width, height = img.shape[1], img.shape[0] seams_to_remove = max([width, height]) - min([width, height]) normal_resize = cv2.resize(img, None, fx=height/width, fy=1, interpolation=cv2.INTER_AREA) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mag = filters.sobel(gray.astype('float')) for numSeams in range(1, seams_to_remove): try: carved = img_as_ubyte(carved) gray = cv2.cvtColor(carved, cv2.COLOR_BGR2GRAY) mag = filters.sobel(gray.astype('float')) carved = transform.seam_carve(carved, mag, direction, 1) except: carved = transform.seam_carve(img, mag, direction, numSeams) carved = img_as_ubyte(carved) if rotate: carved = imutils.rotate_bound(carved, 270) width, height = carved.shape[1], carved.shape[0] carved = cv2.resize(carved, None, fx=target_size/height, fy=target_size/height, interpolation=cv2.INTER_AREA) return carved
def test_seam_carving(): img = np.array([[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 0]], dtype=np.float) expected = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=np.float) energy = 1 - img out = transform.seam_carve(img, energy, 'vertical', 1, border=0) testing.assert_equal(out, expected) img = img.T energy = energy.T out = transform.seam_carve(img, energy, 'horizontal', 1, border=0) testing.assert_equal(out, expected.T)
def get_resized_image(file, ratio): img = util.img_as_float(io.imread(file)) if len(img.shape) >= 3 and img.shape[2] == 4: img = color.rgba2rgb(img) if len(img.shape) == 2: img = color.gray2rgb(img) eimg = filters.sobel(color.rgb2gray(img)) width = img.shape[1] height = img.shape[0] mode, rm_paths = get_lines_to_remove((width, height), ratio) if mode: logger.debug("Carving %s %s paths ", rm_paths, mode) outh = transform.seam_carve(img, eimg, mode, rm_paths) return outh else: return img
def work_work(img, remove_direction, num_of_seam_to_delete, algo_type): # Perform seam carving with save option import cv2 from skimage import transform from algo import my_algorithm direction = remove_direction # vertical/horizontal seams_per_iter = num_of_seam_to_delete # number of pixels to remove each iteration (lower is cleaner) # # images resizing # print(img.shape) # size_change = img.shape # size_change = [int(x * 1) for x in size_change] # img = cv2.resize(img, (size_change[1], size_change[0])) # print(img.shape) energy_map = my_algorithm(img, algo_type) image_result = transform.seam_carve(img, energy_map, direction, seams_per_iter) # current_progress = str(num_of_seam_to_delete) return image_result
def seam_carve(img): """ Seam carve image :param img: PIL image object :return: PIL image object """ # Convert to skimage image img_to_convert = img.copy() img_to_convert = pil_to_skimage(img_to_convert) # Energy Map, used to determine which pixels will be removed eimg = filters.sobel(color.rgb2gray(img_to_convert)) # (height, width) img_dimensions = img_to_convert.shape # Squish width if width >= height, squish height if height > width # Number of pixels to keep along the outer edges (5% of largest dimension) # Number of seams to be removed, (1 to 10% of largest dimension) if img_dimensions[1] >= img_dimensions[0]: mode = "horizontal" border = round(img_dimensions[1] * 0.05) num_seams = random.randint(1, round(0.1*img_dimensions[1])) else: mode = "vertical" border = round(img_dimensions[0] * 0.05) num_seams = random.randint(1, round(0.1*img_dimensions[0])) try: img_to_convert = transform.seam_carve(img_to_convert, eimg, mode, num_seams, border) except Exception as e: print("Unable to seam_carve: " + str(e)) # Convert back to PIL image img_to_convert = skimage_to_pil(img_to_convert) return img_to_convert
def stretch_and_shrink(image, num_steps=40): ''' Stretches an image by some mount and shrinks it back over a one second animation ''' height, width = image.shape[:2] extra = int (width / 10.0) step = int(extra * 1.0 / num_steps) # make sure that step size is even if step % 2 == 1: step = step + 1 images = [image] image = util.img_as_float(image) print('Image size: {}x{}'.format(width, height)) print('Number of seams to be removed: {}, in each iteration: {}'.format(num_steps * step, step)) for i in range(num_steps): print('Iteration: {}'.format(i+1)) #print('Converting to gray scale.') gray_image = color.rgb2gray(image) #print('Computing sobel energy.') energy = filters.sobel(gray_image) #print('Performing seam carving') #print(image.shape) image = transform.seam_carve(image, energy, 'vertical', step) #print('Converting to 8-bit format') image_u8 = util.img_as_ubyte(image) #print('Adding side bars in black') cur_width = image_u8.shape[1] # add pillar box appropriately image_u8 = iv.add_pillar_box_pattern(image_u8, int((width - cur_width)/2)) print(image_u8.shape) #print(image_u8.shape) images.append(image_u8) images_reversed = images[::-1] images.extend(images_reversed) return images
def seam_carve(self): ratio = self.ratio gray = self.gray image = self.image # compute energy map emap = filters.sobel(gray.astype("float")) # shape of image h, w = gray.shape[:2] # 1:1 ratio if ratio == "square": if h >= w: self.direction = "horizontal" self.numseams = h - w elif w > h: self.direction = "vertical" self.numseams = w - h # 16:9 ratio elif ratio == "landscape": if h >= w: self.direction = "horizontal" carved_w = w carved_h = (carved_w * 9) // 16 self.numseams = h - carved_h elif w > h: # if old height can contain the new height (respecting ratio) if (h - ((w * 9) // 16)) >= 0: self.direction = "horizontal" carved_w = w carved_h = (carved_w * 9) // 16 self.numseams = h - carved_h else: self.direction = "vertical" carved_h = h carved_w = (carved_h * 16) // 9 self.numseams = w - carved_w # 9:16 ratio elif ratio == "portrait": if h >= w: # if old width can contain the new width (respecting ratio) if (w - ((h * 9) // 16)) >= 0: self.direction = "vertical" carved_h = h carved_w = (carved_h * 9) // 16 self.numseams = w - carved_w else: self.direction = "horizontal" carved_w = w carved_h = (carved_w * 16) // 9 self.numseams = h - carved_h elif w > h: self.direction = "vertical" carved_h = h carved_w = (carved_h * 9) // 16 self.numseams = w - carved_w carved = transform.seam_carve(image, emap, self.direction, self.numseams) return carved
def image_resize2(request): img = request.GET.get('image', '') ext = img.split('.')[-1] key = request.GET.get('key', '') referer = request.META.get('HTTP_REFERER', '') referer = urlparse(referer).hostname if img == '' or key == '' or referer == '': print('first') imgpath = os.path.join("notallowed.png") image = Image.open(imgpath) response = HttpResponse(content_type="image/jpeg") image.save(response, "JPEG") return response height = request.GET.get('height', '') width = request.GET.get('width', '') if height == '' or width == '': query = Media.objects.filter(image=img).filter( owner__developer__api_management__key=key, owner__developer__api_management__sources__host=referer).first() if query is not None: print('second') imgpath = os.path.join(settings.MEDIA_ROOT, str(query.image)) image = Image.open(imgpath) response = HttpResponse(content_type="image/jpeg") image.save(response, "JPEG") return response else: print('third') imgpath = os.path.join("notallowed.png") image = Image.open(imgpath) response = HttpResponse(content_type="image/jpeg") image.save(response, "JPEG") return response print("Referer", referer) height = int(height) width = int(width) query = Media.objects.filter(image=img).filter( owner__developer__api_management__key=key, owner__developer__api_management__sources__host=referer).first() if query is not None: api_management = APIManagement.objects.filter(key=key).first() if api_management.quota <= 0: imgpath = os.path.join("notallowed.png") image = Image.open(imgpath) response = HttpResponse(content_type="image/jpeg") image.save(response, "JPEG") return response else: api_management.quota -= 1 api_management.save() cache_query = CachedMedia.objects.filter(original=query).filter( height=height).filter(width=width).filter(api_type='1').first() if cache_query is not None: print("HIT") cache_query.last_hit_at = datetime.now() cache_query.save() print(cache_query.image) imgpath = os.path.join(settings.MEDIA_ROOT, str(cache_query.image)) image = Image.open(imgpath) response = HttpResponse(content_type="image/jpeg") image.save(response, "JPEG") return response else: print("Media Found") print(query.width, width, query.height, height) if query.width - width < 0 or query.height - height < 0: raise Http404 imgpath = os.path.join(settings.MEDIA_ROOT, img) image = Image.open(imgpath) np_img = np.array(image) np_img = util.img_as_float(np_img) eimg = filters.sobel(color.rgb2gray(np_img)) out = transform.seam_carve(np_img, eimg, 'horizontal', query.height - height) out = out / out.max() out = out * 255 eimg = filters.sobel(color.rgb2gray(out)) out = transform.seam_carve(out, eimg, 'vertical', query.width - width) out = out / out.max() out = out * 255 out = out.astype(np.uint8) image = Image.fromarray(out) # image = image.resize((width, height), PIL.Image.ANTIALIAS) output = BytesIO() image.save(output, 'JPEG') filecontent = ContentFile(output.getvalue()) media = CachedMedia() media.owner = query.owner media.dislay_name = img + ' Resized' media.public = query.public media.api_type = '1' media.last_hit_at = datetime.now() media.original = query media.image.save('image.jpg', File(filecontent), save=True) response = HttpResponse(content_type="image/jpeg") image.save(response, "JPEG") return response else: print('No matching Image') imgpath = os.path.join("notallowed.png") image = Image.open(imgpath) response = HttpResponse(content_type="image/jpeg") image.save(response, "JPEG") return response
"--direction", type=str, default="vertical", help="seam removal direction") args = vars(ap.parse_args()) # load the image and convert it to grayscale image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # compute the Sobel gradient magnitude representation # of the image -- this will serve as our "energy map" # input to the seam carving algorithm mag = filters.sobel(gray.astype("float")) # show the original image cv2.imshow("Original", image) # loop over a number of seams to remove for numSeams in range(20, 140, 20): # perform seam carving, removing the desired number # of frames from the image -- `vertical` cuts will # change the image width while `horizontal` cuts will # change the image height carved = transform.seam_carve(image, mag, args["direction"], numSeams) print("[INFO] removing {} seams; new size: " "w={}, h={}".format(numSeams, carved.shape[1], carved.shape[0])) # show the output of the seam carving algorithm cv2.imshow("Carved", carved) cv2.waitKey(0)
# but the anothur didn't use theta = image.size()/20, he set theta as a content number : 2 def energyMap(img): x0 = np.roll(img, -1, axis=1).T x1 = np.roll(img, 1, axis=1).T y0 = np.roll(img, -1, axis=0).T y1 = np.roll(img, 1, axis=0).T return simpleEnergy(x0, x1, y0, y1).T # reference : https://github.com/margaret/seam-carver/blob/master/energy_functions.py #=======================================================================================================# if __name__ == '__main__': input_image_name = 'tram.png' source_image = cv2.imread(input_image_name) #contrast_map = calcContrastMap(extend_image,theta) contrast_map = energyMap(source_image) carved = transform.seam_carve(source_image, contrast_map, 'vertical', 50) cv2.imshow('skt_seam_carving_result', carved) new_carved = np.zeros_like(carved) new_carved = cv2.normalize(carved, new_carved, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) cv2.imwrite("skt_seam_carving_result.jpg", new_carved) cv2.waitKey(0)
def seam_carving (image, direction): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) mag = filters.sobel(gray.astype("float")) for num_seam in range(20, 140, 20): carved = transform.seam_carve(image, mag, direction, num_seam) return carved
from skimage import transform from skimage import filters import cv2 import numpy as np img = cv2.imread('images/person.jpeg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) magnitude = filters.sobel(gray.astype('float')) for numSeams in range(20, 140, 20): # carved = transform.seam_carve(img, magnitude, 'horizontal', numSeams) carved = transform.seam_carve(img, magnitude, 'vertical', numSeams, border=80) print("[INFO] removing {} seams; new size: " "w={}, h={}".format(numSeams, carved.shape[1], carved.shape[0])) cv2.imshow('Carved', carved) cv2.imshow('Origin', img) cv2.waitKey() #cv2.imshow('Origin', img) #cv2.waitKey() cv2.destroyAllWindows()
sobel_x = cv2.convertScaleAbs(sobel_x) # get 8bit abs value sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5) # sobel Y sobel_y = cv2.convertScaleAbs(sobel_y) energy_map = cv2.addWeighted(sobel_x, 0.5, sobel_y, 0.5, 0) return energy_map energy_map = create_energy_map(img) cv2.imshow('original', energy_map) cv2.waitKey(0) cv2.destroyAllWindows() for i, num_seams in enumerate(range(seams_per_iter, scale, seams_per_iter)): #Where the actual carving happens. carve = transform.seam_carve(img, energy_map, direction, seams_per_iter) #Where the carved value is removed or something and reset to 'img'. img = (carve * 255).astype( np.uint8) # recursively recalculate images, save time, cleaner cuts #Energy map being created. energy_map = create_energy_map(img) print("removing %d pixels" % (num_seams)) # add padding on right for removed seams (for video in imageJ) # This should be removed for the purpose of AWS Lambda. This way I can get the image file with the dimension that # the carved image is instead of having a black boarder on the right side. #carve = cv2.copyMakeBorder(carve, top=0, bottom=0, left=0, right=num_seams, borderType=cv2.BORDER_CONSTANT, value=[0, 0, 0]) title = 'carved' + str(num_seams) + '.jpg'
#ap.add_argument("-i", "--image", required=True, #help="path to input image file") #ap.add_argument("-d", "--direction", type=str, #default="vertical", help="seam removal direction") #args = vars(ap.parse_args()) # load the image and convert it to grayscale image = cv2.imread('image.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # compute the Sobel gradient magnitude representation # of the image -- this will serve as our "energy map" # input to the seam carving algorithm mag = filters.sobel(gray.astype("float")) # show the original image cv2.imshow("Original", image) # loop over a number of seams to remove for numSeams in range(20, 140, 10): # perform seam carving, removing the desired number # of frames from the image -- `vertical` cuts will # change the image width while `horizontal` cuts will # change the image height carved = transform.seam_carve(image, mag, "vertical", numSeams) print("[INFO] removing {} seams; new size: " "w={}, h={}".format(numSeams, carved.shape[1], carved.shape[0])) # show the output of the seam carving algorithm cv2.imshow("Carved", carved) cv2.waitKey(0)
from skimage import transform from skimage import filters import cv2 image = cv2.imread("test.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) mag = filters.sobel(gray.astype("float")) cv2.imshow("Original", image) for numSeams in range(20, 140, 20): carved = transform.seam_carve(image, mag, 'horizantal', numSeams) print("[INFO] removing {} seams; new size: " "w={}, h={}".format(numSeams, carved.shape[1], carved.shape[0])) cv2.imshow("Carved", carved) cv2.waitKey(0)
def test_seam_carving(): with pytest.raises(NotImplementedError): transform.seam_carve()
eimg = filters.sobel(color.rgb2gray(img)) plt.title('Original Image') plt.imshow(img) ###################################################################### resized = transform.resize(img, (img.shape[0], img.shape[1] - 200), mode='reflect') plt.figure() plt.title('Resized Image') plt.imshow(resized) ###################################################################### out = transform.seam_carve(img, eimg, 'vertical', 200) plt.figure() plt.title('Resized using Seam Carving') plt.imshow(out) ###################################################################### # Resizing distorts the rocket and surrounding objects, whereas seam carving # removes empty spaces and preserves object proportions. # # Object Removal # -------------- # # Seam carving can also be used to remove artifacts from images. This # requires weighting the artifact with low values. Recall lower weights are # preferentially removed in seam carving. The following code masks the # rocket's region with low weights, indicating it should be removed.
en_map = cv2.addWeighted(sobel_x, 0.5, sobel_y, 0.5, 0) return en_map en_map = create_energy_map(img) cv2.imshow('energy map', en_map) cv2.waitKey(0) #set scale factor if direction == 'v': direction = 'vertical' max_dim = img.shape[1] #maximum size of image elif direction == 'h': direction = 'horizontal' max_dim = img.shape[0] def nothing(x): pass cv2.namedWindow('slider') #Make the trackbar, # seams to remove cv2.createTrackbar('c','slider',0,100,nothing) while True: scale = cv2.getTrackbarPos('c', 'slider') scale = float(scale/100.0) pixels_to_rm = int(scale*max_dim) #number of seams to remove carve = transform.seam_carve(img, en_map, direction, pixels_to_rm) cv2.imshow('carved', carve) if cv2.waitKey(1) & 0xFF == ord('q'): #quit break