OpenCV学习笔记4基础:几何变换-改变大小

Posted xietx1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OpenCV学习笔记4基础:几何变换-改变大小相关的知识,希望对你有一定的参考价值。

1. 按比例缩小

我们使用 resize 函数改变图像大小,例如将图像按比例缩小为原来的80%:

import cv2

img = cv2.imread('images/test.jpg')

width = img.shape[1]
height = img.shape[0]

scale = 80
newHeight = int(height * 80 / 100)
newWidth = int(width * 80 / 100)

imgResized = cv2.resize(img, (newWidth, newHeight))
cv2.imshow('Resized', imgResized)
cv2.waitKey(0)

在这里插入图片描述

resize 函数第一个参数是原图像,第二个参数是高和宽组成的 tuple。

2. 放大

我们还可以对图像进行放大:

import cv2

img = cv2.imread('images/test.jpg')

width = img.shape[1]
height = img.shape[0]

scale = 120
newHeight = int(height * scale / 100)
newWidth = int(width * scale / 100)

imgResized = cv2.resize(img, (newWidth, newHeight), interpolation=cv2.INTER_AREA)
cv2.imshow('Upscale', imgResized)
cv2.waitKey(0)

在这里插入图片描述

这里在调用 resize 函数时指定了一个参数 interpolation ,也就是指定 resize 函数的插值方式,有如下几种:

  • INTER_NEAREST – a nearest-neighbor interpolation(最邻近插值)
  • INTER_LINEAR – a bilinear interpolation(双线性插值,这是默认的方法)
  • INTER_AREA – resampling using pixel area relation(基于局部像素的重采样)。对于图像抽取(image decimation)来说,这可能是一个更好的方法。但如果是放大图像时,它和最近邻法的效果类似。
  • INTER_CUBIC – a bicubic interpolation over 4×4 pixel neighborhood(4x4 双三次插值法)
  • INTER_LANCZOS4 – a Lanczos interpolation over 8×8 pixel neighborhood(8x8 多相位图像插值法)

3. 只更改高或宽

可以只更改高或宽,例如只更改高度,采用 INTER_AREA 插值:

import cv2

img = cv2.imread('images/test.jpg')

width = img.shape[1]
height = img.shape[0]

scale = 80
newHeight = int(height * scale / 100)

imgResized = cv2.resize(img, (width, newHeight), interpolation=cv2.INTER_AREA)
cv2.imshow('Resize Height', imgResized)
cv2.waitKey(0)

在这里插入图片描述

4. 缩放到指定大小

可以直接指定大小(像素值),如 300x100:

import cv2

img = cv2.imread('images/test.jpg')

imgResized = cv2.resize(img, (300, 100), interpolation=cv2.INTER_AREA)
cv2.imshow('Resize Specific', imgResized)
cv2.waitKey(0)

在这里插入图片描述


References

  1. OpenCV Doc: Geometric Image Transformations
  2. OpenCV里的INTER_AREA究竟是在做啥?
  3. OpenCV Python – Resize image

QQ交流群:点击链接加入群聊【Python练习生】532232743
我的知乎:AXin啊
公众号:请叫我AXin
在这里插入图片描述

以上是关于OpenCV学习笔记4基础:几何变换-改变大小的主要内容,如果未能解决你的问题,请参考以下文章

OpenCV学习笔记4基础:几何变换-改变大小

OpenCV学习笔记4基础:几何变换-改变大小

OpenCV学习笔记4基础:几何变换-改变大小

OpenCV学习笔记4基础:几何变换-改变大小

OpenCV学习笔记——图像几何变换

Python 大白从零开始 OpenCV 学习课-5. 图像的几何变换