image = cv2.imread('image_'+str(i)+'.jpg', 0)改为批量读取001开头的图片
时间: 2023-12-26 22:05:33 浏览: 109
可以使用以下代码来批量读取以"001"开头的图片:
```
import os
folder_path = "path/to/folder" # 修改为图片所在的文件夹路径
images = []
for file_name in os.listdir(folder_path):
if file_name.startswith("001"):
image = cv2.imread(os.path.join(folder_path, file_name), 0)
images.append(image)
```
这个代码段会读取`folder_path`目录中以"001"开头的所有图片,并将它们存储在`images`列表中。你可以根据你的需求对这些图片进行处理。
相关问题
for i, image_path in enumerate(img_paths): imgcolor = cv2.imread(image_path) imggray = cv2.imread(image_path,0) imggray = cv2.medianBlur(imggray,5) circles = cv2.HoughCircles(imggray,cv2.HOUGH_GRADIENT,1,300,param1=50,param2=30,minRadius=100,maxRadius=int(textavalue)) circles = cv2.HoughCircles(imggray,cv2.HOUGH_GRADIENT,1,300,param1=50,param2=30,minRadius=3,maxRadius=int(textavalue)) circles = np.uint16(np.around(circles)) for i in circles[0,:]: cv2.circle(imgcolor,(i[0],i[1]),i[2],(0,0,255),12) cv2.circle(imgcolor,(i[0],i[1]),2,(0,0,255),12) cv2.imwrite( "zjm" + str(i) + ".jpg", imgcolor) img = cv2.imrea ("zjm"+str(i) + ".jpg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = Image.fromarray(img) # 将数组转为图片 image = img.resize((150, 240)) photo = ImageTk.PhotoImage(image)
这段代码是对图片进行圆检测,并将检测后的图片保存,并读取它们。如果你想修改这段代码,使它能够对文件夹中所有的图片进行圆检测,并将检测后的图片都显示出来,可以按照下面的方式修改:
```
import os
import cv2
from PIL import Image, ImageTk
import tkinter as tk
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, image_path in enumerate(img_paths):
imgcolor = cv2.imread(image_path)
imggray = cv2.imread(image_path,0)
imggray = cv2.medianBlur(imggray,5)
circles = cv2.HoughCircles(imggray,cv2.HOUGH_GRADIENT,1,300,param1=50,param2=30,minRadius=100,maxRadius=int(textavalue))
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
cv2.circle(imgcolor,(i[0],i[1]),i[2],(0,0,255),12)
cv2.circle(imgcolor,(i[0],i[1]),2,(0,0,255),12)
cv2.imwrite("zjm" + str(i) + ".jpg", imgcolor)
root = tk.Tk()
root.title("圆检测图片展示")
for i, image_path in enumerate(img_paths):
img = cv2.imread("zjm" + str(i) + ".jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img) # 将数组转为图片
image = img.resize((150, 240))
photo = ImageTk.PhotoImage(image)
label = tk.Label(image=photo)
label.image = photo
label.grid(row=i//3, column=i%3)
root.mainloop()
```
修改后的代码会对文件夹中所有的 `.jpg` 和 `.webp` 图片进行圆检测,并将检测后的图片保存为 `zjm0.jpg`, `zjm1.jpg` 等等。然后,程序会将所有的图片都显示在一个窗口中,每行显示 3 张图片。你可以根据需要修改图片的大小和每行显示的图片数量。
import cv2 import numpy as np import os # 提取图像的HOG特征 def get_hog_features(image): hog = cv2.HOGDescriptor() hog_features = hog.compute(image) return hog_features # 加载训练数据集 train_data = [r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128"] train_labels = [r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128\labels.txt"] num_samples = 681 for i in range(num_samples): img = cv2.imread(str(i).zfill(3)+'.jpg') hog_features = get_hog_features(image) hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) color_hist = cv2.calcHist([hsv_image], [0, 1], None, [180, 256], [0, 180, 0, 256]) color_features = cv2.normalize(color_hist, color_hist).flatten() train_data.append(hog_features) train_labels.append(labels[i]) # 训练SVM模型 svm = cv2.ml.SVM_create() svm.setType(cv2.ml.SVM_C_SVC) svm.setKernel(cv2.ml.SVM_LINEAR) svm.train(np.array(train_data), cv2.ml.ROW_SAMPLE, np.array(train_labels)) # 对测试图像进行分类 test_image = cv2.imread('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\maskslic2_roi.png', 0) test_features = get_hog_features(test_image) result = svm.predict(test_features.reshape(1,-1)) # 显示分割结果 result_image = np.zeros(test_image.shape, np.uint8) for i in range(test_image.shape[0]): for j in range(test_image.shape[1]): if result[i,j] == 1: result_image[i,j] = 255 cv2.imshow('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\Result.png', result_image) cv2.waitKey(0) cv2.destroyAllWindows()
这段代码似乎存在一些问题。以下是一些可能需要修改的地方:
1. 在加载训练数据时,`train_data`和`train_labels`应该是列表类型,而不是字符串类型。您可以使用`os.listdir()`函数来获取文件夹中的所有图像文件名,并使用`cv2.imread()`函数读取图像文件。
2. 在获取HOG特征时,您应该使用`img`而不是`image`变量。
3. 在提取颜色直方图特征时,您应该使用`test_image`而不是`image`变量。
4. 在将特征添加到`train_data`列表中时,您应该将`hog_features`和`color_features`链接在一起。
5. 在使用`svm.predict()`函数对测试图像进行分类时,您应该使用`svm.predict(test_features)`而不是`svm.predict(test_features.reshape(1,-1))`。
6. 在显示分割结果时,您应该使用`cv2.imshow()`函数的第一个参数是窗口的名称,而不是图像文件的路径。
以下是修改后的示例代码:
```python
import cv2
import numpy as np
import os
# 提取图像的HOG特征
def get_hog_features(img):
hog = cv2.HOGDescriptor()
hog_features = hog.compute(img)
return hog_features.flatten()
# 加载训练数据集
train_folder = r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128"
train_data = []
train_labels = []
for filename in os.listdir(train_folder):
if filename.endswith('.jpg'):
img = cv2.imread(os.path.join(train_folder, filename), 0)
hog_features = get_hog_features(img)
hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
color_hist = cv2.calcHist([hsv_image], [0, 1], None, [180, 256], [0, 180, 0, 256])
color_features = cv2.normalize(color_hist, color_hist).flatten()
features = np.concatenate((hog_features, color_features))
train_data.append(features)
with open(os.path.join(train_folder, 'labels.txt'), 'r') as f:
label = int(f.readline().strip())
train_labels.append(label)
# 训练SVM模型
svm = cv2.ml.SVM_create()
svm.setType(cv2.ml.SVM_C_SVC)
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.train(np.array(train_data), cv2.ml.ROW_SAMPLE, np.array(train_labels))
# 对测试图像进行分类
test_image = cv2.imread('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\maskslic2_roi.png', 0)
test_features = get_hog_features(test_image)
hsv_test_image = cv2.cvtColor(test_image, cv2.COLOR_BGR2HSV)
color_hist = cv2.calcHist([hsv_test_image], [0, 1], None, [180, 256], [0, 180, 0, 256])
color_features = cv2.normalize(color_hist, color_hist).flatten()
test_features = np.concatenate((test_features, color_features))
result = svm.predict(test_features)
# 显示分割结果
result_image = np.zeros(test_image.shape, np.uint8)
for i in range(test_image.shape[0]):
for j in range(test_image.shape[1]):
if result[i,j] == 1:
result_image[i,j] = 255
cv2.imshow('Result', result_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,以上代码仅作为参考。您可能需要根据自己的情况进行微调。
阅读全文