5
votes

I have an image of size 1200 x 800.

I want to extract a square patch from this image given a patch center 500, 450 and a patch scale 23% of the smaller dimension of the image.

Is there any function in opencv, skimage or any library that allows me to do it in python?

1
Yes. This is a simple and common operation and you can do this in OpenCV, skimage, and also PIL and pure numpy. You should pick the library you want to use (probably based on other criteria since they can all do this), try to do it with whatever tool you pick, and then ask a question if you have trouble with that (which you probably won't).tom10
Hint: 23% of smaller dimension is 0.23 * 800.. Rectangle top-left corner is (center_x - width/2, center_y - height/2). For square patch width = height.J0HN
Might be a simple question, but doesn't deserve a negative vote...jason

1 Answers

5
votes

Using OpenCV python, you can do this:

import cv2
import numpy as np

# load the image
image = cv2.imread('path/to/your_image.jpg')

# define some values
patch_center = np.array([500, 450])
patch_scale = 0.23

# calc patch position and extract the patch
smaller_dim = np.min(image.shape[0:2])
patch_size = int(patch_scale * smaller_dim)
patch_x = int(patch_center[0] - patch_size / 2.)
patch_y = int(patch_center[1] - patch_size / 2.)
patch_image = image[patch_x:patch_x+patch_size, patch_y:patch_y+patch_size]

# show image and patch
cv2.imshow('image', image)
cv2.imshow('patch_image', patch_image)
cv2.waitKey()

Notice that this was done step-by-step just to be easier to understand. You can do many of these steps directly.