def process_image(image_path, output_folder): gray = cv2.imread(image_path) edges = cv2.Canny(gray, 50, 150) lines = cv2.HoughLines(edges, 1, np.pi / 180, threshold=90) sum_angle = 0 count = 0 if lines is not None: for line in lines: rho, theta = line[0] angle = theta * 180 / np.pi sum_angle += angle count += 1 avg_angle = sum_angle / count rotated_image = rotate_image(gray, avg_angle) filename = os.path.basename(image_path) output_path = os.path.join(output_folder, filename) cv2.imwrite(output_path, rotated_image) def rotate_image(image, angle): height, width = image.shape[:2] center = (width // 2, height // 2) rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0) rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height)) return rotated_image input_folder = 'img_out_binary' output_folder = 'rotated_img' os.makedirs(output_folder, exist_ok=True) for filename in os.listdir(input_folder): if filename.endswith(".jpg") or filename.endswith(".JPG"): image_path = os.path.join(input_folder, filename) process_image(image_path, output_folder) 优化程序,使程序可以对图片文件名包含汉字的图片进行处理和保存
时间: 2024-04-14 15:31:57 浏览: 142
要使程序能够处理和保存包含汉字的图片文件名,您可以对`process_image()`函数进行修改。在处理图片之前,您可以对文件名进行URL编码,然后使用编码后的文件名来保存旋转后的图片。以下是修改后的代码:
```python
def process_image(image_path, output_folder):
# 对文件名进行URL编码
encoded_filename = urllib.parse.quote(os.path.basename(image_path))
gray = cv2.imread(image_path)
edges = cv2.Canny(gray, 50, 150)
lines = cv2.HoughLines(edges, 1, np.pi / 180, threshold=90)
sum_angle = 0
count = 0
if lines is not None:
for line in lines:
rho, theta = line[0]
angle = theta * 180 / np.pi
sum_angle += angle
count += 1
avg_angle = sum_angle / count
rotated_image = rotate_image(gray, avg_angle)
# 使用编码后的文件名来保存旋转后的图片
output_path = os.path.join(output_folder, encoded_filename)
cv2.imwrite(output_path, rotated_image)
```
在修改后的代码中,首先使用`urllib.parse.quote()`函数对文件名进行编码,然后使用编码后的文件名来构建输出路径。这样可以确保保存的文件名不会受到包含汉字的影响。
另外,确保在程序中正确导入`urllib.parse`模块来使用URL编码函数。
阅读全文