使用 OpenCV 从文件中读取图像

问题描述 投票:0回答:2

我想使用Graphviz Python包将PNG类型的流程图转换为图形。这里我已经使用

pip install opencv-python pytesseract graphviz
安装了相关的包 在我创建了一个 python 文件之后。

import cv2
import pytesseract
import graphviz

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  # Replace with your actual path

# Load the flowchart image
img = cv2.imread('flowchart.png')

# Preprocess the image (adjust as needed)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Extract text from image elements
elements = []
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cntr in contours:
    x, y, w, h = cv2.boundingRect(cntr)
    text = pytesseract.image_to_string(img[y:y+h, x:x+w])
    elements.append({'text': text, 'x': x, 'y': y, 'w': w, 'h': h})

# Create Graphviz graph
graph = graphviz.Digraph(comment='Flowchart Graph')

# Add nodes and edges based on extracted elements
for i, element in enumerate(elements):
    node_id = f'node_{i}'
    graph.node(node_id, label=element['text'], shape='box')  # Adjust shape as needed
    if i > 0:  # Add edges based on element positions (adjust logic as needed)
        graph.edge(f'node_{i-1}', node_id)

# Render the graph
graph.render('flowchart_graph.png', view=True)

当我尝试运行此 python 文件时,vs code 终端出现错误,名为

[ WARN:[email protected]] global loadsave.cpp:248 cv::findDecoder imread_('flowchart.png'): can't open/read file: check file path/integrity
Traceback (most recent call last):
  File "c:\Users\ASUS\Desktop\FYP Docs\flowchart_graph.py", line 11, in <module>
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.8.1) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

但是,flowchart.png 图像与此 python 文件位于同一目录中。 这个错误是什么原因造成的?我该如何解决?

python opencv file-not-found working-directory
2个回答
0
投票

以下是一些可以帮助您的提示:

  1. 检查文件路径: 确保文件路径正确。您可以使用绝对路径来指定图像文件,或者确保图像文件与您的Python脚本位于同一目录中。

    
    img = cv2.imread('flowchart.png')  # Use an absolute path if needed
    
  2. 验证图像文件: 仔细检查图像文件“flowchart.png”是否与 Python 脚本位于同一目录中。另外,请确保文件名拼写正确且大小写匹配。

  3. 检查文件权限: 确保您的 Python 脚本具有读取图像文件所需的权限。如果您在权限受限的环境中运行脚本,请考虑使用提升的权限运行它。

  4. 使用完整路径: 尝试使用图像文件的完整路径。这可确保不存在与工作目录相关的问题。

  
  img = cv2.imread(r'C:\path\to\your\image\flowchart.png')

调试信息: 添加打印语句以输出调试信息,例如当前工作目录以及该目录中的文件列表。这可以帮助您识别与脚本执行环境相关的任何问题。

python

import os

print("Current Working Directory:", os.getcwd())
print("Files in Current Directory:", os.listdir())

运行脚本并检查工作目录和文件列表是否符合您的期望。

图片加载: 如果上述步骤无法解决问题,请考虑检查 OpenCV 是否可以成功加载其他图像。尝试使用相同的脚本加载不同的图像,看看问题是否仍然存在。


    img = cv2.imread('other_image.jpg')  # Replace with the name of another image file

如果有效,则可能表明存在特定于“flowchart.png”文件的问题。

通过完成这些步骤,您应该能够识别并解决问题的根本原因。

希望对您有帮助!

祝你有美好的一天:)

纪尧姆


0
投票

我能够解决这个问题。我在另一个文件夹中,并从该文件夹中运行 Python 代码。这是我的错误

© www.soinside.com 2019 - 2024. All rights reserved.