繁体   English   中英

图像大小(Python、OpenCV)

[英]Image size (Python, OpenCV)

我想在 python 中获取图像大小,就像我用 C++ 做的那样。

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

使用 openCV 和 numpy 就这么简单:

import cv2

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

对我来说,最简单的方法是获取 image.shape 返回的所有值:

height, width, channels = img.shape

如果您不想要通道数(用于确定图像是 bgr 还是灰度),只需删除该值:

height, width, _ = img.shape

将模块cv的函数GetSize与您的图像一起用作参数。 它以包含 2 个元素的元组形式返回宽度、高度:

width, height = cv.GetSize(src)

我使用 numpy.size() 来做同样的事情:

import numpy as np
import cv2

image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)

来自本教程: https : //www.tutorialkart.com/opencv/python/opencv-python-get-image-size/

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]

来自其他教程: https : //www.pyimagesearch.com/2018/07/19/opencv-tutorial-a-guide-to-learn-opencv/

图像 = cv2.imread("jp.png")

(h, w, d) = image.shape

在发布答案之前,请仔细检查。

这是一个返回图像尺寸的方法:

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)

我相信简单的img.shape[-1::-1]会更好。

您可以使用image.shape来获取图像的尺寸。 它返回 3 个值。 第一个值是图像的高度,第二个是宽度,最后一个是通道数。 您不需要此处的最后一个值,因此您可以使用以下代码来获取图像的高度和宽度:

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

我们可以使用frame = cv2.resize(frame, (width,height))这是一个简单的例子-

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM