批量检测图像白边并保存白边图像
时间: 2023-07-04 07:14:04 浏览: 73
批量检测图像白边并保存白边图像的方法类似于批量检测图像白边的方法,只需要在白边检测代码中添加保存白边图像的功能即可。代码示例如下:
```python
import cv2
import numpy as np
import os
def detect_white_edge(img_path, output_dir):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
white_pixels = np.sum(hist[255:])
total_pixels = gray.shape[0] * gray.shape[1]
white_ratio = white_pixels / total_pixels
if white_ratio < 0.01:
print(f'{img_path}: 图像没有白边')
else:
print(f'{img_path}: 图像有白边')
white_mask = (gray == 255).astype(np.uint8) * 255 # 生成白边掩码
white_edge = cv2.bitwise_and(img, img, mask=white_mask) # 提取白边图像
output_path = os.path.join(output_dir, os.path.basename(img_path))
cv2.imwrite(output_path, white_edge)
if __name__ == '__main__':
img_dir = 'image_dir'
output_dir = 'white_edge_dir'
if not os.path.exists(output_dir):
os.mkdir(output_dir)
for img_file in os.listdir(img_dir):
img_path = os.path.join(img_dir, img_file)
detect_white_edge(img_path, output_dir)
```
在这个例子中,我们在白边检测代码中添加了保存白边图像的功能。具体来说,当检测到图像有白边时,我们首先生成白边掩码,然后利用掩码提取白边图像,并保存到指定目录下。在主函数中,我们遍历指定目录下的所有图像文件,对每张图像调用`detect_white_edge`函数即可。注意,我们需要先创建保存白边图像的目录,否则会引发文件系统错误。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)