v9.1.1
Menu

Crop Image

easyFREEBook OverviewImage ProcessingCV: Introduction to Computer Vision

Implement a function to extract a rectangular region from an image, given the top-left corner coordinates (row,col)(row, col) and the dimensions (height,width)(height, width). This task involves image processing and region of interest extraction.

The concept of cropping an image is fundamental in computer vision, as it allows for focusing on specific parts of an image, reducing noise, and improving processing efficiency. In mathematical terms, the cropped image can be represented as a subset of the original image pixels, defined by the bounds row≤y<row+heightrow \leq y < row + height and col≤x<col+widthcol \leq x < col + width (the end bounds are excluded, like Python slicing).

To achieve this, consider the following steps:

  1. Identify the top-left corner coordinates (row,col)(row, col).
  2. Determine the dimensions (height,width)(height, width) of the region to be extracted.
  3. Extract the sub-image using the specified bounds.
Cropped Image={(x,y)∣row≤y<row+height,col≤x<col+width}\text{Cropped Image} = \{(x, y) | row \leq y < row + height, col \leq x < col + width\}

This technique is widely used in image editing and object detection applications.

Example

Input
crop([[1,2,3],[4,5,6],[7,8,9]], 0, 0, 2, 2)
Output
[[1,2],[4,5]]
Reasoning
  • Input: image is a 3×33 \times 3 grid of pixel values, rows top to bottom: (1,2,3)(1,2,3), (4,5,6)(4,5,6), (7,8,9)(7,8,9). row =0=0 and col =0=0 put the top-left corner of the crop at the very first pixel; height =2=2 and width =2=2 ask for a 2×22 \times 2 window.
  • Row range: keep rows yy with 0≤y<0+20 \le y < 0 + 2, so rows 00 and 11. The upper bound is exclusive.
  • Column range: keep columns xx with 0≤x<0+20 \le x < 0 + 2, so columns 00 and 11. Column 22 (3,6,93, 6, 9) is dropped.
  • Output: the pixels at those rows and columns, still arranged row by row: (1,2)(1,2) from row 00 and (4,5)(4,5) from row 11, giving [[1, 2], [4, 5]]. The result has exactly height rows of width values each.
  • Notice that the crop keeps each pixel's value and relative position. Only the coordinates shift: the corner (row,col)(row, col) becomes (0,0)(0, 0). With row =1=1, col =1=1 the same 2×22 \times 2 window would land on the bottom-right, (5,6)(5,6) and (8,9)(8,9).

Constraints

  • The crop region must be within image bounds
  • Return the cropped sub-image

Learn this in

More from CV: Introduction to Computer Vision

solution.py

Test results

Sign in to run your code against the test cases.