[英]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.