形状检测项目:多矩形对应QML文件仅生成最后一个的问题求助
Hey there! Let's figure out why only the last .qml file is showing up even though your console says n files should be generated. This is a super common issue, and it almost always boils down to file naming or write logic—let's break it down step by step.
Most Likely Cause: Overwriting the Same File
The biggest culprit here is probably that you're using the exact same filename every time you write a .qml file in your loop. For example, if your code looks like this inside the rectangle detection block:
if shape == "rectangle": x,y,w,h = cv2.boundingRect(contour) with open("rectangle.qml", "w") as f: f.write(your_qml_template)
Every time the loop runs, it opens rectangle.qml in write mode ("w"), which erases the existing file content and replaces it with the new rectangle's data. By the end of the loop, only the last rectangle's data remains.
Fix: Use Unique Filenames
You need to give each .qml file a distinct name. Here are a few easy ways:
- Add a loop index (e.g.,
rectangle_1.qml,rectangle_2.qml):# Initialize a counter before your loop rect_count = 0 # Inside your shape detection loop if shape == "rectangle": rect_count += 1 x,y,w,h = cv2.boundingRect(contour) filename = f"rectangle_{rect_count}.qml" with open(filename, "w") as f: f.write(your_qml_template) - Use the rectangle's coordinates for uniqueness (e.g.,
rect_x100_y200.qml):if shape == "rectangle": x,y,w,h = cv2.boundingRect(contour) filename = f"rect_x{x}_y{y}.qml" with open(filename, "w") as f: f.write(your_qml_template)
Other Possible Issues to Check
Incorrect Working Directory
Spyder might be saving files to a different folder than you expect. To confirm, add this line before writing files to print your current working directory:import os print("Current working directory:", os.getcwd())If it's not your target folder, either change Spyder's working directory (via the bottom-right corner or
os.chdir("your/target/folder")) or use absolute file paths when saving.Write Logic Outside the Loop
Double-check that your file-writing code is inside the loop that processes each rectangle. If you're collecting all rectangle data first and then writing once at the end (without unique filenames), you'll only get one file.Missing Folder Creation
If you're saving to a specific subfolder, make sure the folder exists before writing files. Add this line to create the folder if it doesn't:os.makedirs("your_output_folder", exist_ok=True)
Example Working Code Snippet
Here's a quick example tying it all together:
import cv2 import os # Set up output folder output_dir = "detected_rectangles" os.makedirs(output_dir, exist_ok=True) # Assume you have your image loaded and contours detected img = cv2.imread("your_image.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) rect_count = 0 for contour in contours: # Approximate contour to check if it's a rectangle approx = cv2.approxPolyDP(contour, 0.02*cv2.arcLength(contour, True), True) if len(approx) == 4: rect_count += 1 x, y, w, h = cv2.boundingRect(approx) # Generate QML content qml_content = f''' Rectangle {{ x: {x} y: {y} width: {w} height: {h} border.color: "blue" border.width: 2 }} ''' # Save with unique filename file_path = os.path.join(output_dir, f"rectangle_{rect_count}.qml") with open(file_path, "w") as qml_file: qml_file.write(qml_content) print(f"Generated: {file_path}")
Run this, and you should see all your .qml files in the detected_rectangles folder, one for each detected rectangle.
内容的提问来源于stack exchange,提问作者newbie

