1、读取图片并进行灰度处理,最后展示图片。 2、将图片进行二值化处理,并展示图片。 3、截取原图片的某个区域(区域自选),并进行图像的保存。 4、将原图片进行平滑处理(使用均值、方框、高斯以及中值滤波进行
时间: 2024-04-30 15:21:21 浏览: 136
1. 读取图片并进行灰度处理,最后展示图片。
```python
import cv2
# 读取图片
img = cv2.imread('test.jpg')
# 将图片转换为灰度图
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 展示图片
cv2.imshow('Gray Image', gray_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
2. 将图片进行二值化处理,并展示图片。
```python
import cv2
# 读取图片
img = cv2.imread('test.jpg')
# 将图片转换为灰度图
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 对灰度图进行二值化处理
threshold_value = 127
max_value = 255
ret, binary_img = cv2.threshold(gray_img, threshold_value, max_value, cv2.THRESH_BINARY)
# 展示图片
cv2.imshow('Binary Image', binary_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
3. 截取原图片的某个区域(区域自选),并进行图像的保存。
```python
import cv2
# 读取图片
img = cv2.imread('test.jpg')
# 获取图片的高和宽
height, width = img.shape[:2]
# 定义截取区域的左上角和右下角坐标
x1, y1 = int(width * 0.25), int(height * 0.25)
x2, y2 = int(width * 0.75), int(height * 0.75)
# 截取区域
cropped_img = img[y1:y2, x1:x2]
# 保存截取的图片
cv2.imwrite('cropped_img.jpg', cropped_img)
# 展示截取的图片
cv2.imshow('Cropped Image', cropped_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
4. 将原图片进行平滑处理(使用均值、方框、高斯以及中值滤波进行)。
```python
import cv2
# 读取图片
img = cv2.imread('test.jpg')
# 进行均值滤波
kernel_size = (5, 5)
mean_blur_img = cv2.blur(img, kernel_size)
# 进行方框滤波
box_filter_size = 5
box_blur_img = cv2.boxFilter(img, -1, (box_filter_size, box_filter_size))
# 进行高斯滤波
gaussian_blur_size = (5, 5)
gaussian_blur_sigma_x = 0
gaussian_blur_img = cv2.GaussianBlur(img, gaussian_blur_size, gaussian_blur_sigma_x)
# 进行中值滤波
median_blur_size = 5
median_blur_img = cv2.medianBlur(img, median_blur_size)
# 展示平滑处理后的图片
cv2.imshow('Mean Blur Image', mean_blur_img)
cv2.imshow('Box Blur Image', box_blur_img)
cv2.imshow('Gaussian Blur Image', gaussian_blur_img)
cv2.imshow('Median Blur Image', median_blur_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文
相关推荐


















