Obtención do tamaño da imaxe (ancho e alto) con Python, OpenCV e Pillow (PIL)

Negocios

En Python hai varias bibliotecas para manexar imaxes, como OpenCV e Pillow (PIL). Nesta sección explícase como obter o tamaño da imaxe (ancho e alto) para cada unha delas.

Podes obter o tamaño da imaxe (ancho e alto) como unha tupla usando forma para OpenCV e tamaño para Pillow (PIL), pero teña en conta que a orde de cada un é diferente.

A seguinte información ofrécese aquí.

  • OpenCV
    • ndarray.shape:Obter o tamaño da imaxe (ancho, alto)
      • Para imaxes en cor
      • Para imaxes en escala de grises (monocromáticas).
  • Pillow(PIL)
    • size,width,height:Obter o tamaño da imaxe (ancho, alto)

Consulte o seguinte artigo sobre como obter o tamaño (capacidade) dun ficheiro en lugar do tamaño da imaxe (tamaño).

OpenCV:ndarray.shape:Obter o tamaño da imaxe (ancho, alto)

Cando se carga un ficheiro de imaxe en OpenCV, trátase como un ndarray de matriz NumPy, e o tamaño da imaxe (ancho e alto) pódese obter a partir da forma do atributo, que indica a forma do ndarray.

Non só en OpenCV, senón tamén cando se carga un ficheiro de imaxe en Pillow e se converte nun ndarray, o tamaño da imaxe representado polo ndarray obtense mediante a forma.

Para imaxes en cor

No caso das imaxes en cor, utilízase o seguinte ndarray tridimensional.

  • Fila (altura)
  • Fila (ancho)
  • Cor (3)

a forma é unha tupla dos elementos anteriores.

import cv2

im = cv2.imread('data/src/lena.jpg')

print(type(im))
# <class 'numpy.ndarray'>

print(im.shape)
print(type(im.shape))
# (225, 400, 3)
# <class 'tuple'>

Para asignar cada valor a unha variable, desempaquete a tupla do seguinte xeito.

h, w, c = im.shape
print('width:  ', w)
print('height: ', h)
print('channel:', c)
# width:   400
# height:  225
# channel: 3

_
Ao desempaquetar unha tupla, o anterior pódese asignar convencionalmente como unha variable para os valores que non se usarán despois. Por exemplo, se non se utiliza o número de cores (número de canles), utilízase o seguinte.

h, w, _ = im.shape
print('width: ', w)
print('height:', h)
# width:  400
# height: 225

Tamén se pode usar tal e como está especificándoo por índice (índice) sen asignalo a unha variable.

print('width: ', im.shape[1])
print('height:', im.shape[0])
# width:  400
# height: 225

(width, height)
Se queres obter esta tupla, podes usar slice e escribir o seguinte: cv2.resize(), etc. Se queres especificar o argumento por tamaño, úsao.

print(im.shape[1::-1])
# (400, 225)

Para imaxes en escala de grises (monocromáticas).

No caso de imaxes en escala de grises (monocromáticas), utilízase o seguinte ndarray bidimensional.

  • Fila (altura)
  • Fila (ancho)

A forma será esta tupla.

im_gray = cv2.imread('data/src/lena.jpg', cv2.IMREAD_GRAYSCALE)

print(im_gray.shape)
print(type(im_gray.shape))
# (225, 400)
# <class 'tuple'>

Basicamente o mesmo que para as imaxes en cor.

h, w = im_gray.shape
print('width: ', w)
print('height:', h)
# width:  400
# height: 225

print('width: ', im_gray.shape[1])
print('height:', im_gray.shape[0])
# width:  400
# height: 225

Se queres asignar o ancho e o alto ás variables, podes facelo do seguinte xeito, tanto se a imaxe está en cor como en escala de grises.

h, w = im.shape[0], im.shape[1]
print('width: ', w)
print('height:', h)
# width:  400
# height: 225

(width, height)
Se queres obter esta tupla, podes usar franxas e escribila do seguinte xeito. Pódese utilizar o seguinte estilo de escritura tanto se a imaxe está en cor como en escala de grises.

print(im_gray.shape[::-1])
print(im_gray.shape[1::-1])
# (400, 225)
# (400, 225)

Pillow(PIL):size, width, height:Obter o tamaño da imaxe (ancho, alto)

O obxecto de imaxe obtido ao ler unha imaxe con Pillow(PIL) ten os seguintes atributos.

  • size
  • width
  • height

O tamaño é a seguinte tupla.
(width, height)

from PIL import Image

im = Image.open('data/src/lena.jpg')

print(im.size)
print(type(im.size))
# (400, 225)
# <class 'tuple'>

w, h = im.size
print('width: ', w)
print('height:', h)
# width:  400
# height: 225

Tamén pode obter o ancho e o alto respectivamente como atributos.
width,height

print('width: ', im.width)
print('height:', im.height)
# width:  400
# height: 225

O mesmo ocorre coas imaxes en escala de grises (monocromáticas).

im_gray = Image.open('data/src/lena.jpg').convert('L')

print(im.size)
print('width: ', im.width)
print('height:', im.height)
# (400, 225)
# width:  400
# height: 225
Copied title and URL