图像分割和图像缩放的py文件
时间: 2024-01-21 22:03:30 浏览: 65
图像缩小.py
以下是图像分割和图像缩放的Python代码示例:
图像分割:
```python
import cv2
# 读取图像
img = cv2.imread('image.jpg')
# 将图像转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 应用二值化
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# 执行形态学操作
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# 找到轮廓
contours, hierarchy = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
# 显示图像
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
图像缩放:
```python
import cv2
# 读取图像
img = cv2.imread('image.jpg')
# 获取图像的尺寸
height, width = img.shape[:2]
# 定义缩放比例
scale_percent = 50
# 计算缩放后的新尺寸
new_width = int(width * scale_percent / 100)
new_height = int(height * scale_percent / 100)
new_size = (new_width, new_height)
# 缩放图像
resized_img = cv2.resize(img, new_size, interpolation=cv2.INTER_AREA)
# 显示图像
cv2.imshow('Image', resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文