When I try to run my code in PyCharm, it exits with code 0, and gives the desired output, but when I try to run it in VS Code it gives the following error:
File "c:\Users\1\Desktop\ImagetoText\ITT2.py", line 21, in <module> img = cv.cvtColor(img, cv.COLOR_BGR2RGB) cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-kh7iq4w7\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
How it is possible that the same code runs without errors or warnings relating to this line in PyCharm while not working in VS Code or directly in W10 is alien to my understanding.
Note: I have tried tweaking the path but to no avail.
Code:
from glob import glob
from io import BytesIO
import pytesseract
import cv2 as cv
from tkinter import *
import pyperclip
import os
presentItem = ImageGrab.grabclipboard()
with BytesIO() as f:
presentItem.save(f, format='PNG')
presentItem.save('tempITT' + '.png', 'PNG')
pytesseract.pytesseract.tesseract_cmd = 'C:\\Users\\1\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe'
img = cv.imread(r"C:\Users\1\Desktop\ImagetoText\tempITT.png")
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
imgtext = pytesseract.image_to_string(img)
pyperclip.copy(imgtext)
os.remove(r"C:\Users\1\Desktop\ImagetoText\tempITT.png")
Firts check if you really have this image.
C:\Users\1\Desktop\ImagetoText\tempITT.png
imread doesn't show error when it can't find image but it returns None and later code run cv.cvtColor(None, cv.COLOR_BGR2RGB) which gives error with text !_src.empty()
I think all your problem starts with presentItem.save(...) because you use filename without full path - so it may save it in local folder, not in C:\Users\1\Desktop\ImagetoText, and later imread(r'C:\Users\1\Desktop\ImagetoText\...) can't find it.
You should use full path in all functions
presentItem.save(r'C:\Users\1\Desktop\ImagetoText\tempITT.png', 'PNG')
BTW:
When you have code C:\Users\1\Desktop\ImagetoText and you run it from this folder
cd C:\Users\1\Desktop\ImagetoText
python script.py
then presentItem.save("tempITT.png") saves file in this folder C:\Users\1\Desktop\ImagetoText and you have C:\Users\1\Desktop\ImagetoText\tempITT.png,
but if you run code for other folder
cd other folder
python C:\Users\1\Desktop\ImagetoText\script.py
then presentItem.save("tempITT.png") saves file in other foler you have C:\other folder\tempITT.png
And this can happend in your situation. Different tools may runs it in different way and later presentItem.save( may save file in different folder - and you should use full path in presentItem.save()
Folder in which code is executed is called Current Working Directory and you can see it using print( os.getcwd() )
Related
This question already has answers here:
Load local data files to Colaboratory
(9 answers)
Closed 4 months ago.
I am following a tutorial to load data from a local file using Google Colaboratory.
Here is my code:
import numpy as np #To do relay operations
import matplotlib.pyplot as plt #to show image
import os #Iterate through directories and join paths
import cv2 #To do image operations
DATADIR = "C:\\Users\\Family\\Desktop\\Nottingham\\Year 4\\FYP\\Software\\Datasets\\PetImages"
CATEGORIES = ["Dog","Cat"]
for category in CATEGORIES:
path = os.path.join(DATADIR,category) #path to cats or dogs dir
print(category)
print(path)
for img in os.listdir(path):
print(img)
img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
plt.imshow(img_array, cmap = "gray")
plt.show()
break
break
However, I am getting the following error in Line 13:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Family\Desktop\Nottingham\Year 4\FYP\Software\Datasets\PetImages/Dog'`
I have verified multiple times that this directory indeed exists, yet the same error continues to happen.
I tried changing the format of the directory in DATADIR, by trying these three methods:
DATADIR = "C:\\Users\\Family\\Desktop\\Nottingham\\Year 4\\FYP\\Software\\Datasets\\PetImages"
DATADIR = "C:/Users/Family/Desktop/Nottingham/Year 4/FYP/Software/Datasets/PetImages"
DATADIR = r"C:\Users\Family\Desktop\Nottingham\Year 4\FYP\Software\Datasets\PetImages"
However, none of these methods seemed to work. What else can I try?
If you are on Google collab, just in the left pane go to the directory and right-click, copy path. But if you are on your PC (Not Google Collab)
I am not sure, I faced this problem before and this is my solution:
Go to this directory
Open the cmd in this directory and write python
write the following code to get the exact path of this directory:
>>>import os
>>>os.getcwd()
You will get the full path, copy it and use it
Hope this helps
I have imported the zip files for the said directories, but every time I try to visualize the images with a random number I am getting the following error:
error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
The code I use:
img = imread_collection(os.path.join(self.img_dir, self.img_IDs[i]))
#img = cv2.imread()
img = cv2.cvtColor(np.float32(img), cv2.COLOR_BGR2RGB)
The error means that you not have read the image(s).
To read an image you need to have following lines of code:
img = cv2.imread('./some path to image/image.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
Can your function read images like the standard opencv imread module?
Can you show us the content of this function?
imread_collection(os.path.join(self.img_dir, self.img_IDs[i]))
You could print the result of os.path to see if the folder is without any errors in name:
print( os.path.join(self.img_dir, self.img_IDs[i]) )
Don't forget to mount the drive:
from google.colab import drive
drive.mount('/content/drive')
I wanted to make a script that will convert images stored in a folder to video.
Here's the code:
import cv2
import numpy as np
import os
import pyautogui
import msvcrt
imageFolder = input('Please enter images folder path: ').replace(chr(34),"")
outputPath = imageFolder+'\Video.avi'
try:
images = [img for img in os.listdir(imageFolder) if img.endswith(".jpg")]
while len(images)==0:
imageFolder = input('There are no images in the directory ! Please enter images folder path: ').replace(chr(34),"")
images = [img for img in os.listdir(imageFolder) if img.endswith(".jpg")]
print('Creating recording...')
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
frame = cv2.imread(os.path.join(imageFolder, images[0]))
height, width, layers = frame.shape
frameRate = 2
video = cv2.VideoWriter(outputPath, fourcc, frameRate, (width,height))
for image in images:
print(f'{int((images.index(image)/len(images))*100)} %', end="\r")
video.write(cv2.imread(os.path.join(imageFolder, image)))
cv2.destroyAllWindows()
video.release()
decision = input('Recording has been created successfully ! Do you want to open it? [Y/N]: ')
if decision.lower() == 'y':
print('Opening file...')
os.startfile(outputPath)
except:
print(f'There was a problem with creating a recording. Check images path: {imageFolder}')
The code works fine when I'm launching that from command line, but after converting that to EXE with pyinstalller (pyinstaller -F ConvertToRecording.py) I'm getting an error like this:
[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (3
92) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cp
p:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the n
ame of file): C:\Users\MyUser\Documents\Test\20191018_12_45\Video.avi in function
'cv::icvExtractPattern'
Any help appreciated !
I met the same problem. Just go to your OpenCV folder (if you don't have, go here: https://opencv.org/releases/) and find the opencv_videoio_ffmpeg420_64.dll ( I am using 4.20) file. copy it and paste it to your exe direction (same folder).
Then it will work.
Use the os.path module to with paths instead of concatenating strings. This ensures a better cross-platform compatibility. See the manual for a more elaborate explanation of the module.
for f, tags in tqdm(df_test.values, miniters=1000):
img = cv2.imread('input/test-jpg/{}.jpg'.format(f), -1)
x_test.append(cv2.resize(img, (img_size, img_size)))
x_test = np.array(x_test, np.float32)/255.
When i run the above code I get this error:
error: OpenCV(3.4.3)
C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:4044:
error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'
but the files there are in the directory and the path is rigth
Make sure your input folder is located on the same level as your .py file. Otherwise, use abolute paths.
Also try the following to find your current working directory:
import os
os.getcwd()
check what is inside img after you do cv2.imread..
I am trying to execute this script
from PIL import Image
im = Image.open("image.jpg")
nx, ny = im.size
It is working fine when I run it in python shell
pytesser_v0.0.1]#env python
>>> from PIL import Image
>>> im = Image.open("image.jpg")
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=46x24 at 0x7FA4688F16D0>
but when I put it in a some test.py file and run it like python test.py
I am getting this error
File "test1.py", line 17, in <module>
im = Image.open("image.jpg")
File "/usr/local/python.2.7.11/lib/python2.7/site-packages/PIL/Image.py", line 2309, in open
% (filename if filename else fp))
IOError: cannot identify image file 'image.jpg'
please help me with this issue, Thanks
PS: Earlier I installed PIL from Imaging-1.1.7 setup.py, later I installed Pillow, I think the problem was in the mutual presence of the PIL and Pillow library on the machine.
Seems like PIL library haven't fixed this bug yet.
Here is my solution:
Open image using OpenCV library, then convert it to PIL image
from PIL import Image
import cv2
image_path = 'Folder/My_picture.jpg'
# read image using cv2 as numpy array
cv_img = cv2.imread(image_path)
# convert the color (necessary)
cv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
# read as PIL image in RGB
pil_img = Image.fromarray(cv_img).convert('RGBA')
Then you can operate with it as with a regular PIL image object.
Make sure that "image.jpg" is in the same directory as "test1.py".
If it isn't then you could either move it, or put the correct directory inside of Image.open().
I have the same issue.
This is because the test.py does not have the same pathname. If you are working in the same folder it will work.
However, the solution i found was to put in the full path + file name so that it is unambiguous.
"c:\...fullpath...\image.jpg"
You can do it like this:
from PIL import Image
import os
curDir = os.getcwd()
fileName = "image.jpg"
fn = curDir + "\\" + fileName
print(fn)
image = Image.open(fn)
image.show()
This works. Please let me know if you find better.