灰度图像下采样的代码
时间: 2023-09-10 20:09:48 浏览: 67
下面是一个用Python实现的灰度图像下采样的代码示例:
```python
import cv2
import numpy as np
# 读取原始图像
img = cv2.imread('lena-hd.png')
# 将图像转换为灰度图
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 获取图像高度和宽度
height = gray_img.shape\[0\]
width = gray_img.shape\[1\]
# 采样转换成16x16区域
numHeight = int(height/16)
numWidth = int(width/16)
# 创建一幅图像
new_img = np.zeros((height, width), np.uint8)
# 图像循环采样16x16区域
for i in range(16):
# 获取Y坐标
y = i * numHeight
for j in range(16):
# 获取X坐标
x = j * numWidth
# 获取填充颜色(左上角像素点的灰度值)
color = gray_img\[y, x\]
# 循环设置小区域采样
for n in range(numHeight):
for m in range(numWidth):
new_img\[y+n, x+m\] = color
# 显示图像
cv2.imshow("Original", gray_img)
cv2.imshow("Downsampled", new_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这段代码首先读取原始图像,然后将图像转换为灰度图。接下来,根据图像的高度和宽度计算出采样区域的大小。然后,创建一个与原始图像大小相同的新图像。接下来,通过循环遍历原始图像中的每个采样区域,并将该区域内的像素点的灰度值赋值给新图像中对应的像素点。最后,显示原始图像和下采样后的图像。
请注意,这只是一个示例代码,实际应用中可能需要根据具体需求进行适当的修改。
#### 引用[.reference_title]
- *1* [MATLAB图像处理(一):图像转灰度图及图像采样和量化](https://blog.csdn.net/wmz_Gavin/article/details/128444194)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [[Python从零到壹] 四十一.图像处理基础篇之图像采样处理](https://blog.csdn.net/Eastmount/article/details/122812908)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]