Python Forum
Using OpenCV and image path is invalid
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using OpenCV and image path is invalid
#1
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.
deanhystad write Feb-21-2024, 04:37 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
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)
Reply
#3
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
Reply
#4
(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]]
Reply
#5
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-...ta-mining/
Reply
#6
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,224 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  how to detect horizontal dotted lines in an image using OpenCV pframe 0 4,894 Apr-15-2020, 08:53 PM
Last Post: pframe
  zlib decompress error: invalid code lengths set / invalid block type DreamingInsanity 0 6,881 Mar-29-2020, 12:44 PM
Last Post: DreamingInsanity
  Display the bottom image of the line and cut the upper image using Opencv jenkins43 1 3,254 May-27-2019, 06:56 AM
Last Post: heiner55
  .pth file does not show up in sys.path when configuring path. arjunsingh2908 2 5,780 Jul-03-2018, 11:16 AM
Last Post: arjunsingh2908
  OpenCV, segment image Standard_user 6 7,682 Jan-01-2017, 08:29 PM
Last Post: Standard_user

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020