Image size (Python, OpenCV)

徘徊边缘 提交于 2020-01-10 09:14:05

问题


I would like to get the Image size in python,as I do it with c++.

int w = src->width;
printf("%d", 'w');

回答1:


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)



回答2:


Using openCV and numpy it is as easy as this:

import cv2

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



回答3:


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)



回答4:


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:

height, width, _ = img.shape



回答5:


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: {width:<int>, height=<int>, size_bytes=<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)



回答6:


We can use frame = cv2.resize(frame, (width,height)) here is a simple example -

import cv2
import numpy as np


frame = cv2.imread("temp/i.jpg")
frame = cv2.resize(frame, (500,500))
cv2.imshow('frame', frame)



if cv2.waitKey(1) & 0xFF == ord('q'):
    break
cv2.destroyAllWindows()


来源:https://stackoverflow.com/questions/13033278/image-size-python-opencv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!