img_paths = [os.path.join(image_path, f) for f in os.listdir(image_path) if f.endswith(".jpg") or (".webp")] for i, img_path in enumerate(img_paths): im = cv2.imread(img_path) gray_img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) canny = cv2.Canny(gray_img, 30, 150) lines = cv2.HoughLines(canny, 1, np.pi / 180, 180) lines1 = lines[:, 0, :] for rho, theta in lines1[:]: a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 3000 * (-b)) y1 = int(y0 + 3000 * (a)) x2 = int(x0 - 3000 * (-b)) y2 = int(y0 - 3000 * (a)) cv2.line(im, (x1, y1), (x2, y2), (0, 0, 255), 2) cv2.imwrite("zjm" +str(i) + ".jpg", im) img = cv2.imread( "zjm"+str(i) + ".jpg")修改这段代码使它能够历遍文件夹里所有图片,并将每张图片都进行直线检测,然后将直线检测后的图片都保存下来,并读取它们
时间: 2024-03-26 07:39:46 浏览: 73
修改后的代码如下:
```
import os
import cv2
import numpy as np
image_path = "path/to/your/image/folder"
img_paths = [os.path.join(image_path, f) for f in os.listdir(image_path) if f.endswith(".jpg") or f.endswith(".webp")]
for i, img_path in enumerate(img_paths):
im = cv2.imread(img_path)
gray_img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(gray_img, 30, 150)
lines = cv2.HoughLines(canny, 1, np.pi / 180, 180)
if lines is not None:
lines1 = lines[:, 0, :]
for rho, theta in lines1[:]:
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 3000 * (-b))
y1 = int(y0 + 3000 * (a))
x2 = int(x0 - 3000 * (-b))
y2 = int(y0 - 3000 * (a))
cv2.line(im, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.imwrite("zjm" + str(i) + ".jpg", im)
img_list = []
for i, img_path in enumerate(img_paths):
img = cv2.imread("zjm" + str(i) + ".jpg")
img_list.append(img)
print("所有图片处理完成!")
```
这段代码会遍历包含在 `image_path` 文件夹中的所有 `.jpg` 和 `.webp` 图片,对每张图片进行直线检测,并将直线检测后的图片保存为 `zjm0.jpg`, `zjm1.jpg` 等等。最后,程序会读取所有保存的图片并将它们存储在 `img_list` 列表中。
阅读全文