更正代码,因为代码出现以下异常:cv2.error: OpenCV(3.4.8) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
时间: 2023-07-21 19:53:01 浏览: 213
好的,以下是更正后的代码:
```python
import cv2
import numpy as np
# 读取原始图像
img = cv2.imread('image.jpg')
if img is None: # 判断图像是否读取成功
print('Failed to read image!')
else:
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# 获取直线
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
# 计算角度
angles = []
for line in lines:
for rho, theta in line:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
angle = np.arctan2(y2-y1, x2-x1)
angles.append(angle)
# 计算平均角度
avg_angle = np.mean(angles)
# 旋转校正
rows, cols = img.shape[:2]
M = cv2.getRotationMatrix2D((cols/2, rows/2), avg_angle*180/np.pi, 1)
corrected_img = cv2.warpAffine(img, M, (cols, rows))
# 显示结果
cv2.imshow('Original Image', img)
cv2.imshow('Corrected Image', corrected_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这里加入了判断语句,如果无法读取图像,则会输出错误信息。
阅读全文