opencv 裁剪图片方法详解

OpenCV 是一个用于计算机视觉和机器学习的开源库。它包含了很多图像处理的功能,包括裁剪图片。在 Python 中,我们可以使用 OpenCV 的 `cv2` 模块来实现图片的裁剪。
以下是使用 OpenCV 裁剪图片的详细步骤:
1. 导入所需的库:
```python
import cv2
```
2. 读取图片:
```python
image = cv2.imread('path/to/your/image.jpg')
```
3. 获取图片的宽度和高度:
```python
height, width, _ = image.shape
```
4. 定义裁剪区域:
```python
start_row, start_col = int(height * 0.25), int(width * 0.25)
end_row, end_col = int(height * 0.75), int(width * 0.75)
```
这里,我们将图片的左上角和右下角分别设置为原始图片的 1/4 和 3/4 处。你可以根据需要调整这些值。
5. 裁剪图片:
```python
cropped_image = image[start_row:end_row, start_col:end_col]
```
6. 显示裁剪后的图片:
```python
cv2.imshow('Cropped Image', cropped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
7. 保存裁剪后的图片:
```python
cv2.imwrite('path/to/save/cropped_image.jpg', cropped_image)
```
将以上代码整合到一起,你可以得到一个完整的裁剪图片的程序:
```python
import cv2
# 读取图片
image = cv2.imread('path/to/your/image.jpg')
# 获取图片的宽度和高度
height, width, _ = image.shape
# 定义裁剪区域
start_row, start_col = int(height * 0.25), int(width * 0.25)
end_row, end_col = int(height * 0.75), int(width * 0.75)
# 裁剪图片
cropped_image = image[start_row:end_row, start_col:end_col]
# 显示裁剪后的图片
cv2.imshow('Cropped Image', cropped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 保存裁剪后的图片
cv2.imwrite('path/to/save/cropped_image.jpg', cropped_image)
```
这就是使用 OpenCV 裁剪图片的方法。希望对你有所帮助!

以下是几段常用的 OpenCV 裁剪图片的代码:

1. 裁剪指定区域的图片
```python
import cv2
# 读取图片
img = cv2.imread('image.jpg')
# 指定裁剪区域
x, y, w, h = 100, 100, 200, 200
# 裁剪图片
crop_img = img[y:y+h, x:x+w]
# 显示裁剪后的图片
cv2.imshow('crop_img', crop_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
2. 根据比例裁剪图片
```python
import cv2
# 读取图片
img = cv2.imread('image.jpg')
# 获取图片尺寸
height, width = img.shape[:2]
# 指定裁剪比例
scale = 0.5
# 计算裁剪区域
x, y, w, h = int(width*(1-scale)/2), int(height*(1-scale)/2), int(width*scale), int(height*scale)
# 裁剪图片
crop_img = img[y:y+h, x:x+w]
# 显示裁剪后的图片
cv2.imshow('crop_img', crop_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
3. 根据目标尺寸裁剪图片
```python
import cv2
# 读取图片
img = cv2.imread('image.jpg')
# 指定目标尺寸
target_width, target_height = 200, 200
# 调整图片尺寸
resized_img = cv2.resize(img, (target_width, target_height))
# 显示调整后的图片
cv2.imshow('resized_img', resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```

猜你喜欢

转载自blog.csdn.net/qq_42751978/article/details/130843731
今日推荐