Read image from a file using OpenCV

Question:

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 FilesTesseract-OCRtesseract.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:[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:UsersASUSDesktopFYP Docsflowchart_graph.py", line 11, in <module>
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.8.1) D:aopencv-pythonopencv-pythonopencvmodulesimgprocsrccolor.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?

Answers:

Here are some tips that could help you :

  1. Check File Path:
    Ensure that the file path is correct. You can use an absolute path to specify the image file or make sure that the image file is in the same directory as your Python script.

    
    img = cv2.imread('flowchart.png')  # Use an absolute path if needed
    
  2. Verify Image File:
    Double-check that the image file "flowchart.png" is present in the same directory as your Python script. Also, make sure that the file name is spelled correctly and matches the case.

  3. Check File Permissions:
    Ensure that your Python script has the necessary permissions to read the image file. If you’re running the script in an environment with restricted permissions, consider running it with elevated privileges.

  4. Use Full Path:
    Try using the full path to the image file. This ensures that there are no issues related to the working directory.

  
  img = cv2.imread(r'C:pathtoyourimageflowchart.png')

Debugging Information:
Add print statements to output debugging information, such as the current working directory and the list of files in that directory. This can help you identify any issues related to the script’s execution environment.

python

import os

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

Run the script and check if the working directory and the list of files match your expectations.

Image Loading:
If the above steps don’t resolve the issue, consider checking if OpenCV can load other images successfully. Try loading a different image using the same script to see if the problem persists.


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

If this works, it may indicate an issue specific to the "flowchart.png" file.

By going through these steps, you should be able to identify and address the root cause of the issue.

Hope it helped you !

Have a good day 🙂

Guillaume

Answered By: Gpommerey

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