Python cv img size

Image size (Python, OpenCV)

For accessing an object’s properties like in PHP? If so, why don’t they just use the dot operator ( . )?

it’s called dereferencing, and allows us to access to the value of the variable pointed by the * operator

8 Answers 8

Using openCV and numpy it is as easy as this:

import cv2 img = cv2.imread('path/to/img',0) height, width = img.shape[:2] 

For me the easiest way is to take all the values returned by image.shape:

height, width, channels = img.shape 

if you don’t want the number of channels (useful to determine if the image is bgr or grayscale) just drop the value:

Use the function GetSize from the module cv with your image as parameter. It returns width, height as a tuple with 2 elements:

width, height = cv.GetSize(src) 

I use numpy.size() to do the same:

import numpy as np import cv2 image = cv2.imread('image.jpg') height = np.size(image, 0) width = np.size(image, 1) 
import cv2 # read image img = cv2.imread('/home/ubuntu/Walnut.jpg', cv2.IMREAD_UNCHANGED) # get dimensions of image dimensions = img.shape # height, width, number of channels in image height = img.shape[0] width = img.shape[1] channels = img.shape[2] 

Please double check things before posting answers.

Here is a method that returns the image dimensions:

from PIL import Image import os def get_image_dimensions(imagefile): """ Helper function that returns the image dimentions :param: imagefile str (path to image) :return dict (of the form: , height=, size_bytes=) """ # Inline import for PIL because it is not a common library with Image.open(imagefile) as img: # Calculate the width and hight of an image width, height = img.size # calculat ethe size in bytes size_bytes = os.path.getsize(imagefile) return dict(width=width, height=height, size_bytes=size_bytes) 

I believe simply img.shape[-1::-1] would be nicer.

You can use image.shape to get the dimensions of the image. It returns 3 values. The first value is height of an image, the second is width, and the last one is number of channels. You don’t need the last value here so you can use below code to get height and width of image:

height, width = src.shape[:2] print(width, height) 

Источник

Get Image Size in OpenCV Python

In this OpenCV Tutorial, we will learn how to get image size in OpenCV Python using NumPy Array shape property, with an example.

Читайте также:  Html data url image

OpenCV Python – Get Image Size

In Image Processing applications, it is often necessary to know the size of an image that is loaded or transformed through various stages.

When working with OpenCV Python, images are stored in numpy ndarray. To get the image shape or size, use ndarray.shape to get the dimensions of the image. Then, you can use index on the dimensions variable to get width, height and number of channels for each pixel.

In the following code snippet, we have read an image to img ndarray. And then we used ndarray.shape to get the dimensions of the image.

img = cv2.imread('/path/to/image.png') dimensions = img.shape

Example

In this example, we have read an image and used ndarray.shape to get the dimension.

OpenCV Python - Get Image Size Shape

We can access height, width and number of channels from img.shape: Height is at index 0, Width is at index 1; and number of channels at index 2.

Python Program

import cv2 # read image img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED) # get dimensions of image dimensions = img.shape # height, width, number of channels in image height = img.shape[0] width = img.shape[1] channels = img.shape[2] print('Image Dimension : ',dimensions) print('Image Height : ',height) print('Image Width : ',width) print('Number of Channels : ',channels)
Image Dimension : (149, 200, 4) Image Height : 149 Image Width : 200 Number of Channels : 4

img.shape returns (Height, Width, Number of Channels)

  1. Height represents the number of pixel rows in the image or the number of pixels in each column of the image array.
  2. Width represents the number of pixel columns in the image or the number of pixels in each row of the image array.
  3. Number of Channels represents the number of components used to represent each pixel.

In the above example, Number of Channels = 4 represent Alpha, Red, Green and Blue channels.

Conclusion

Concluding this OpenCV Python Tutorial, we have learnt how to get the image shape using OpenCV ndarray.shape.

Источник

OpenCV Resize image using cv2.resize()

In this OpenCV tutorial, we learn the syntax of cv2.resize() and how to use this function to resize a given image. We can use cv2.resize() function to upscale, downscale, or resize to a desired size (considering or not considering the aspect ratio).

OpenCV Python – Resize image

Resizing an image means changing the dimensions of it, be it width alone, height alone or changing both of them. Also, the aspect ratio of the original image could be preserved in the resized image. To resize an image, OpenCV provides cv2.resize() function.

Syntax of cv2.resize()

The syntax of resize function in OpenCV is

cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])

OpenCV Python - Resize image

1. Downscale – Resize and Preserve Aspect Ratio

resize-image.py

import cv2 img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED) print('Original Dimensions : ',img.shape) scale_percent = 60 # percent of original size width = int(img.shape[1] * scale_percent / 100) height = int(img.shape[0] * scale_percent / 100) dim = (width, height) # resize image resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) print('Resized Dimensions : ',resized.shape) cv2.imshow("Resized image", resized) cv2.waitKey(0) cv2.destroyAllWindows()
Original Dimensions : (149, 200, 4) Resized Dimensions : (89, 120, 4)

The original image with dimensions [149 x 200 x 4] has been resized to [89, 120, 4] using resize() function.

Читайте также:  String ignore case kotlin

OpenCV Python cv2.resize() - Resize image

2. Upscale – Resize and Preserve Aspect Ratio

In the following example, scale_percent value holds the percentage by which image has to be scaled. Providing a value >100 upscales the image provided.

resize-image.py

import cv2 img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED) print('Original Dimensions : ',img.shape) scale_percent = 220 # percent of original size width = int(img.shape[1] * scale_percent / 100) height = int(img.shape[0] * scale_percent / 100) dim = (width, height) # resize image resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) print('Resized Dimensions : ',resized.shape) cv2.imshow("Resized image", resized) cv2.waitKey(0) cv2.destroyAllWindows()
Original Dimensions : (149, 200, 4) Resized Dimensions : (327, 440, 4)

OpenCV Python - Resize image

3. Resize only width and do not preserve Aspect Ratio

In this example, we provided a specific value in pixels for width and left the height unchanged.

resize-image.py

import cv2 img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED) print('Original Dimensions : ',img.shape) width = 440 height = img.shape[0] # keep original height dim = (width, height) # resize image resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) print('Resized Dimensions : ',resized.shape) cv2.imshow("Resized image", resized) cv2.waitKey(0) cv2.destroyAllWindows()
Original Dimensions : (149, 200, 4) Resized Dimensions : (149, 440, 4)

As we have increased only the width, the output image looks stretched horizontally.

OpenCV Python - Resize image

4. Resize only height and do not preserve Aspect Ratio

In the following example, scale_percent value holds the percentage by which height has to be scaled. Or you may also provide a specific value in pixels.

resize-image.py

import cv2 img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED) print('Original Dimensions : ',img.shape) width = img.shape[1] # keep original width height = 440 dim = (width, height) # resize image resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) print('Resized Dimensions : ',resized.shape) cv2.imshow("Resized image", resized) cv2.waitKey(0) cv2.destroyAllWindows()
Original Dimensions : (149, 200, 4) Resized Dimensions : (440, 200, 4)

As we have increased only the height, the output image looks stretched vertically.

OpenCV Python - Resize image

5. Resize to specific width and height

In the following example, we shall provide specific value in pixels for both width and height.

resize-image.py

import cv2 img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED) print('Original Dimensions : ',img.shape) width = 350 height = 450 dim = (width, height) # resize image resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) print('Resized Dimensions : ',resized.shape) cv2.imshow("Resized image", resized) cv2.waitKey(0) cv2.destroyAllWindows()
Original Dimensions : (149, 200, 4) Resized Dimensions : (450, 350, 4)

OpenCV Python - Resize image

Conclusion

Concluding this OpenCV Python Tutorial, we have learned how to resize an image in Python using OpenCV resize() function.

Читайте также:  Php is valid file path

Источник

Python OpenCV2 (cv2) wrapper to get image size?

How to get the size of an image in cv2 wrapper in Python OpenCV (numpy). Is there a correct way to do that other than numpy.shape() . How can I get it in these format dimensions: (width, height) list?

numpy.shape is not callable. It’s just a plain tuple . Unfortunatelly, it can be either 3 or 2 elements long.

3 Answers 3

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape . Assuming you are working with BGR images, here is an example:

>>> import numpy as np >>> import cv2 >>> img = cv2.imread('foo.jpg') >>> height, width, channels = img.shape >>> print height, width, channels 600 800 3 

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

Oh, come on. Instead of assuming that the image will be BGR or mono, just write generally — h, w = img.shape[:2] , especially as the OP is not interested in the depth. (Neither was I). See my answer for more details.

If you’re only interested in height and width, a more pythonic alternative to @TomaszGandor’s comment would be python h, w, _ = img.shape

I’m afraid there is no «better» way to get this size, however it’s not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array’s shape. If you opt for readability, or don’t want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size :

import numpy as np import cv2 # . def cv_size(img): return tuple(img.shape[1::-1]) 

If you’re on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1]) >>> cv_size(img) (640, 480) 

Writing functions with def is not fun while working interactively.

Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]) , and we need (width, height) , as e.g. cv2.resize expects, so — we must use [1::-1] . Even less memorable than [:2] . And who remembers reverse slicing anyway?

Python 3 tuple unpacking

After we all moved to Python 3, and thus have this https://peps.python.org/pep-3132/ — we can also get h and w by using tuple unpacking:

This time, we need not worry about single channel images 🙂

Источник

Оцените статью