Home > Back-end >  Python syntax question - colon preceding a variable name
Python syntax question - colon preceding a variable name

Time:10-29

I'm in the process of learning some ML concepts using OpenCV, and I have a piece of python code that I was given to translate into c . I have a very basic knowledge of python, and I've run into some syntax that I can't seem to find the meaning for.

I have a variable being passed into a method (whole method not shown) that is coming from the result of cv2.imread(), so an image. In c , it's of type Mat:

def preprocess_image(img, side = 96):
    min_side = min(img.shape[0], img.shape[1])
    img = img[:min_side, :min_side * 2]

I have a couple questions:

  1. What does the syntax ":min_side" do?
  2. What is that line doing in terms of the image?

CodePudding user response:

The line:

img = img[:min_side, :min_side * 2]

is cropping the image so that the resulting image is min_side in height and min_side * 2 in width. The colon preceding a variable name is python's slicing syntax. Observe:

arr = [1, 2, 3, 4, 5, 6]
length = 4
print(arr[:length])

Output:

[1, 2, 3, 4]

CodePudding user response:

:min_side is a shorthand for 0:min_side i.e it produces a slice the object from the start to min_side. For example:

 f = [2, 4, 5, 6, 8, 9]
 f[:3]  # returns [2,4,5]

img = img[:min_side, :min_side *2] produces a crop of the image (which is a numpy array) from 0 to min_side along the height and from 0 to min_side * 2 along the width. Therefore the resulting image would be one of width min_side * 2 and height min_side .

CodePudding user response:

I am assuming the input of the image is a Matrix.

1.What does the syntax ":min_side" do?

  • It Slices the List/Array or basically in this case, a Matrix.

2.What is that line doing in terms of the image?

  • It is resizing the 2D Array( Basically a Matrix)

A simple example of slicing:

input_array = [11, 12, 13, 14, 15]
print(input_array [:2])

output: [11, 12]

  • Related