Python Forum
Using OpenCV and image path is invalid - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Using OpenCV and image path is invalid (/thread-41642.html)



Using OpenCV and image path is invalid - AudunNilsen - Feb-21-2024

Trying to retrieve data from images using four modules.

This is the error message:
Error:
>>> %Run -c $EDITOR_CONTENT Traceback (most recent call last): File "<string>", line 6 image = cv2.imread(“C:\Users\Audun Nilsen\Pictures\pica.webp”) ^ SyntaxError: invalid character in identifier >>>
This is the code:
import cv2  # OpenCV for image processing
import NumPy as np  # NumPy for numerical computations
from skimage import io, feature, segmentation  # Scikit-image for image processing and analysis
import matplotlib.pyplot as plt  # Matplotlib for visualization

image = cv2.imread(“C:\Users\Audun Nilsen\Pictures\pica.webp”)
 
 
 
 
# Convert to grayscale if needed
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
 
# Apply preprocessing techniques (e.g., resizing, noise reduction, contrast enhancement)
resized_image = cv2.resize(gray, (256, 256))

edges = feature.canny(resized_image)  # Edge detection
segments = segmentation.slic(resized_image, n_segments=100)  # Superpixel segmentation
texture_features = feature.local_binary_pattern(resized_image, 8, 1)  # Texture analysis


edge_histogram = np.histogram(edges.ravel(), bins=256)[0]
texture_histogram = np.histogram(texture_features.ravel(), bins=256)[0]

# Calculate statistics (mean, median, standard deviation) across multiple images

mean_edge_histogram = np.mean([edge_histogram1, edge_histogram2, …], axis=0)

kmeans = KMeans(n_clusters=4)
clusters = kmeans.fit_predict(texture_features)

model = SVC()

model.fit(training_features, training_labels)

predictions = model.predict(test_features)

# Use similarity measures (e.g., Euclidean distance, cosine similarity)

distances = np.linalg.norm(query_features – database_features, axis=1
)
Is there something I should put before this code, like you do in HTML ?

I also wonder where the output of this would be. I´ve just copy pasted it, and never used Python before.


RE: Using OpenCV and image path is invalid - Pedroski55 - Feb-21-2024

Don't know what the rest of your code is supposed to do, but the image displays ok like this:

import cv2 

image2display = '/home/pedro/Pictures/aphrodite.jpg'
def myApp(impath):      
    image = cv2.imread(impath) 
    window_name = 'Press any key to quit!'   
    cv2.imshow(window_name, image)     
    cv2.waitKey(0) 
    cv2.destroyAllWindows() 
In Idle or other IDE, import cv2, then call myApp()

myApp(image2display)



RE: Using OpenCV and image path is invalid - deanhystad - Feb-21-2024

Do not use "\" as a path separator. "\" is used to start escape sequences in a string literal, so using it as a path separator can cause a lot of confusion. Use "/" or "\\" instead. you can also use a "raw" string that ignores "\" as a special character.
image = cv2.imread(r"C:\Users\Audun Nilsen\Pictures\pica.webp")
This is a problem:
image = cv2.imread(“C:\Users\Audun Nilsen\Pictures\pica.webp”)
Those may look like double quotes around C:\Users\Audun Nilsen\Pictures\pica.webp, but they are not. This is easy to see if we print the ordinal value for those characters and compare against the ordinal value (ascii value) of double quotes.
not_quotes = r'“C:\Users\Audun Nilsen\Pictures\pica.webp”'

print(ord(not_quotes[0]), ord(not_quotes[-1]), ord('"'[0]))
Output:
8220 8221 34
Why are you running your code this way?
Quote:>>> python script_name.py



RE: Using OpenCV and image path is invalid - snippsat - Feb-21-2024

(Feb-21-2024, 11:15 AM)AudunNilsen Wrote: I also wonder where the output of this would be. I´ve just copy pasted it, and never used Python before.
Basic problem as deanhystad pointed out.
So do you know how to run Python and install with pip?
Simplify the the code,then need to only install opencv-python first.
import cv2

image = cv2.imread('image.webp')
# Convert to grayscale if needed
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply preprocessing techniques (e.g., resizing, noise reduction, contrast enhancement)
resized_image = cv2.resize(gray, (256, 256))
print(resized_image)
So from cmd i gone test Python installation and run this file.
This is how it should look when all works.
# Test Python and pip
C:\code\cv_test>python --version
Python 3.12.2
C:\code\cv_test>pip --version
pip 24.0 from C:\Python312\Lib\site-packages\pip (python 3.12)

# Both files in same folder
C:\code\cv_test>dir
 Volume in drive C is OS
 Volume Serial Number is 3E22-9971

 Directory of C:\code\cv_test

21.02.2024  20:14    <DIR>          .
21.02.2024  20:14    <DIR>          ..
21.02.2024  20:01             1 165 cv_test.py
21.02.2024  17:31           176 972 image.webp
               2 File(s)        178 137 bytes
               2 Dir(s)  202 562 715 648 bytes free

# Run file
C:\code\cv_test>python cv_test.py
[[103 103 103 ... 103 103 103]
 [105 105 105 ... 104 104 104]
 [106 106 106 ... 104 104 104]
 ...
 [ 52  44  44 ...  58  46  53]
 [ 42  39  27 ... 118  46  93]
 [ 66  25  31 ...  54  81 116]]



RE: Using OpenCV and image path is invalid - AudunNilsen - Mar-18-2024

Hi again

Sorry for the late reply.

I don´t know what you mean by the Run C-thing.

I did the change as instructed, and then I got a new error message.

>>> %Run 'open cv - tot.py'
Traceback (most recent call last):
File "C:\Users\Audun Nilsen\open cv - tot.py", line 1, in <module>
import cv2 # OpenCV for image processing
ModuleNotFoundError: No module named 'cv2'
>>>

I have Python 3.12, and this guide that I´m following says CV is included.

https://finnstats.com/2024/01/17/python-for-image-based-data-mining/


RE: Using OpenCV and image path is invalid - snippsat - Mar-18-2024

(Mar-18-2024, 03:47 PM)AudunNilsen Wrote: Sorry for the late reply.

I don´t know what you mean by the Run C-thing.

I did the change as instructed, and then I got a new error message.

>>> %Run 'open cv - tot.py'
Traceback (most recent call last):
File "C:\Users\Audun Nilsen\open cv - tot.py", line 1, in <module>
import cv2 # OpenCV for image processing
ModuleNotFoundError: No module named 'cv2'
>>>
As this work you use Jupyert Notbook or a Idle that support magic commands as %Run.
You most installl opencv-python pip install opencv-python.
Usally the normal way of running Python script from command line,is to run with python command.
python cv_test.py
Output:
[[103 103 103 ... 103 103 103] [105 105 105 ... 104 104 104] [106 106 106 ... 104 104 104] ... [ 52 44 44 ... 58 46 53] [ 42 39 27 ... 118 46 93] [ 66 25 31 ... 54 81 116]]
You should know abot cmd tutorial is the basic Windows command line.
Here can run to test that python an pip work.
C:\>python --version
Python 3.12.2
C:\>pip --version
pip 24.0 from C:\Python312\Lib\site-packages\pip (python 3.12)
Install with pip.
C:\>pip install opencv-python --upgrade
Collecting opencv-python
  Downloading opencv_python-4.9.0.80-cp37-abi3-win_amd64.whl.metadata (20 kB)
Collecting numpy>=1.21.2 (from opencv-python)
  Downloading numpy-1.26.4-cp312-cp312-win_amd64.whl.metadata (61 kB)
     ---------------------------------------- 61.0/61.0 kB 461.8 kB/s eta 0:00:00
Downloading opencv_python-4.9.0.80-cp37-abi3-win_amd64.whl (38.6 MB)
   ---------------------------------------- 38.6/38.6 MB 13.9 MB/s eta 0:00:00
Downloading numpy-1.26.4-cp312-cp312-win_amd64.whl (15.5 MB)
   ---------------------------------------- 15.5/15.5 MB 6.2 MB/s eta 0:00:00
Installing collected packages: numpy, opencv-python
Successfully installed numpy-1.26.4 opencv-python-4.9.0.80
Look at this basic stuff,and explain what you use run to run Python