def deal_threshold(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) Imgaepil = Image.fromarray(gray) # 边缘检测 edges = cv2.Canny(gray, 50, 150) # 使用霍夫变换检测直线 lines = cv2.HoughLines(edges, 1, np.pi / 180, threshold=70) sumang = 0 thresh = None if (lines is not None): for line in lines: anglep = line[0][1] * 180 / np.pi if (anglep > 90): anglep = 180 - anglep print(anglep) sumang = sumang + anglep angle = sumang / len(lines) thresh = Imgaepil.rotate(angle) return thresh def process_images(input_folder, output_folder): # 创建输出文件夹 os.makedirs(output_folder, exist_ok=True) # 遍历输入文件夹中的图片 for filename in os.listdir(input_folder): if filename.endswith(".jpg") or filename.endswith(".png") or filename.endswith(".JPG"): # 读取图片 image_path = os.path.join(input_folder, filename) image = cv2.imread(image_path) # 处理图片 thresh = deal_threshold(image) # 保存处理后的图片 output_path = os.path.join(output_folder, filename) cv2.imwrite(output_path, thresh) print(f"Processed {filename}") # 指定输入文件夹和输出文件夹 input_folder = "img_out_binary" output_folder = "rotated_img" # 调用函数进行处理 process_images(input_folder, output_folder),程序执行后提示 cv2.imwrite(output_path, thresh) cv2.error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:783: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite',优化程序
时间: 2024-02-14 20:28:43 浏览: 30
在你的代码中,出现了一个错误,即 `cv2.imwrite` 报错:`cv2.error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:783: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'`。这个错误通常表示尝试保存一个空图像。
要优化你的程序,可以添加一些错误处理和调试步骤来排查问题。以下是一些可能的优化措施:
1. 检查 `deal_threshold` 函数中是否正确处理了所有情况。确保 `thresh` 不会为空,并且在返回之前对其进行了正确的处理。
2. 在 `process_images` 函数中,检查是否成功读取了图像并确保图像不为空。你可以尝试在读取图像之后添加一些条件语句,以确保图像加载成功。
3. 确保输出文件夹正确创建,并检查保存图像的路径是否正确。你可以添加一些调试语句来输出路径和变量的值,以确保它们符合预期。
4. 如果问题仍然存在,你可以尝试使用其他方法保存图像,例如使用PIL库(`Pillow`)中的 `Image.fromarray` 和 `Image.save` 函数代替 `cv2.imwrite`。
通过以上优化步骤,你应该能够解决保存图像时出现的错误。请记得在处理图像之前先检查图像的加载情况,并确保所有的变量和路径都正确。