python cv2 scale
时间: 2023-10-04 13:08:17 浏览: 106
在Python的OpenCV库中,可以使用cv2.resize()函数来进行图像的缩放。通过指定缩放后的图像大小,可以将原始图像缩放到所需的尺寸。下面是一个示例代码:
```python
import cv2
image = cv2.imread("D:/cv2Demo/lotus2.png") # 读取图像
width = int(image.shape[1] * 0.5) # 缩放后的宽度
height = int(image.shape[0] * 0.5) # 缩放后的高度
resized_image = cv2.resize(image, (width, height)) # 缩放图像
cv2.imwrite("D:/cv2Demo/lotus2Quarter.png", resized_image) # 保存缩放后的图像
```
这段代码将读取名为"lotus2.png"的图像,然后将其缩小为原始图像宽度和高度的一半,并将缩放后的图像保存为"lotus2Quarter.png"。
相关问题
pythoncv2.puttext函数显示中文
`cv2.putText` 是 OpenCV (Python 版本) 中的一个函数,用于在图像上添加文本。如果你想在 Python 中使用这个函数显示中文字符,你需要特别处理文本编码和字体支持。
首先,确保安装了支持中文的字体文件,比如 "SimHei" 或 "simsun.ttc"。然后,在调用 `puttext` 函数时,需要将文本转换为能够正确显示的字节形式。这里通常会使用 UTF-8 编码:
```python
import cv2
import numpy as np
# 获取支持中文的字体路径,例如:
font_path = 'simhei.ttf'
# 创建一个中文字符串
chinese_text = '你好,世界'
# 将文本转换为 bytes,使用 UTF-8 编码
text_bytes = chinese_text.encode('utf-8')
# 定义位置、颜色等参数
position = (50, 50)
color = (0, 0, 255) # 红色
font_scale = 1
# 加载字体并创建一个描边样式
font = cv2.FONT_HERSHEY_SIMPLEX
thickness = 2
# 使用 putText 显示中文
image = cv2.putText(img, text_bytes.decode(), position, font, font_scale, color, thickness)
cv2.imshow('Image with Chinese Text', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意,如果字体路径不正确或者系统找不到该字体,可能会导致无法显示中文。另外,虽然 `decode()` 方法可以尝试将字节解码,但在某些环境下,可能还需要额外处理,如在 Windows 上可能需要使用 `cv2.putText(cv2.Capture.fromId(-1), chinese_text, ...)` 代替。
python cv2库具体用法
Python的OpenCV库(cv2)是一个流行的计算机视觉库,它包含了许多用于图像处理和计算机视觉的函数。下面是一些cv2库的用法:
1. 读取图像
```
import cv2
img = cv2.imread('image_path')
```
2. 显示图像
```
import cv2
img = cv2.imread('image_path')
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
3. 保存图像
```
import cv2
img = cv2.imread('image_path')
cv2.imwrite('output_image_path',img)
```
4. 图像缩放
```
import cv2
img = cv2.imread('image_path')
resized_img = cv2.resize(img,(new_width,new_height))
```
5. 图像旋转
```
import cv2
img = cv2.imread('image_path')
rows,cols = img.shape[:2]
M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,scale)
rotated_img = cv2.warpAffine(img,M,(cols,rows))
```
这些仅仅是cv2库的一部分用法,还有许多其他功能可以探索。
阅读全文
相关推荐
















