pythonopencvfile-not-foundworking-directory

Read image from a file using OpenCV


I want to convert PNG type flowchart to the graph by using Graphviz Python Package. Here I have already installed relevant packages by using pip install opencv-python pytesseract graphviz After I created a python file.

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)

When I tried to run this python file there is an error in vs code terminal called

[ WARN:0@0.452] 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'

However, flowchart.png image is in same directory with this python file. What is caused for this error and how can i solve it?


Solution

  • I was able to solve this. I was in a different folder and from that folder I ran the Python code. It was my mistake