Problems with file path - python

I am trying to load a file from the following path:
path = 'C:/Users/Aman/Alzheimer/test-network/ADNI1_Complete_1Yr_1.5T/ADNI/002_S_0685/MPR__GradWarp__B1_Correction__N3__Scaled/2006-07-06_10_36_49.0/ADNI_002_S_0685_MR_MPR__GradWarp__B1_Correction__N3__Scaled_Br_20070216235850690_S16309_I40683.nii'
However, the file is not loading. If I move the file 1 level up and change the path to
path = 'C:/Users/Aman/Alzheimer/test-network/ADNI1_Complete_1Yr_1.5T/ADNI/002_S_0685/MPR__GradWarp__B1_Correction__N3__Scaled/2006-07-06_10_36_49.0/S16309/ADNI_002_S_0685_MR_MPR__GradWarp__B1_Correction__N3__Scaled_Br_20070216235850690_S16309_I40683.nii'
it loads.
The only difference is the S13893 folder.
I have the following code:
import nibabel as nib
import matplotlib.pyplot as plt
from scipy.misc import imsave as imsave
path = 'C:/Users/Aman/Alzheimer/test-network/ADNI1_Complete_1Yr_1.5T/ADNI/002_S_0685/MPR__GradWarp__B1_Correction__N3__Scaled/2006-07-06_10_36_49.0/ADNI_002_S_0685_MR_MPR__GradWarp__B1_Correction__N3__Scaled_Br_20070216235850690_S16309_I40683.nii'
im = nib.load(path).get_data()
print(im.shape)
any help would be great.

I tried using r in the beginning of the path, however it didn't work.
Also, I tried using \\?\ which again didn't work.
As a final resort, I found out that it was actually an issue with the path length and shortened the path by removing commonalities in the path for all files and it worked fine.
Thanks for all the help.
However, this is just a workaround I performed and the suggested edits/changes didn't work for me.

In Windows you should try with:
path = r'C:/Users/Aman/Alzheimer/test-network/ADNI1_Complete_1Yr_1.5T/ADNI/002_S_0685/MPR__GradWarp__B1_Correction__N3__Scaled/2006-07-06_10_36_49.0/ADNI_002_S_0685_MR_MPR__GradWarp__B1_Correction__N3__Scaled_Br_20070216235850690_S16309_I40683.nii'

Related

Python - images to video [duplicate]

cv2.imread is always returning NoneType.
I am using python version 2.7 and OpenCV 2.4.6 on 64 bit Windows 7.
Maybe it's some kind of bug or permissions issue because the exact same installation of python and cv2 packages in another computer works correctly. Here's the code:
im = cv2.imread("D:\testdata\some.tif",CV_LOAD_IMAGE_COLOR)
I downloaded OpenCV from http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv. Any clue would be appreciated.
First, make sure the path is valid, not containing any single backslashes. Check the other answers, e.g. https://stackoverflow.com/a/26954461/463796.
If the path is fixed but the image is still not loading, it might indeed be an OpenCV bug that is not resolved yet, as of 2013. cv2.imread is not working properly under Win32 for me either.
In the meantime, use LoadImage, which should work fine.
im = cv2.cv.LoadImage("D:/testdata/some.tif", CV_LOAD_IMAGE_COLOR)
In my case the problem was the spaces in the path. After I moved the images to a path with no spaces it worked.
Try changing the direction of the slashes
im = cv2.imread("D:/testdata/some.tif",CV_LOAD_IMAGE_COLOR)
or add r to the begining of the string
im = cv2.imread(r"D:\testdata\some.tif",CV_LOAD_IMAGE_COLOR)
I also met the same issue before on ubuntu 18.04.
cv2.imread(path)
I solved it when I changed the path argument from Relative_File_Path to Absolute_File_Path.
Hope it be useful.
just stumbled upon this one.
The solution is very simple but not intuitive.
if you use relative paths, you can use either '\' or '/' as in test\pic.jpg or test/pic.jpg respectively
if you use absolute paths, you should only use '/' as in /.../test/pic.jpg for unix or C:/.../test/pic.jpg for windows
to be on the safe side, just use for root, _, files in os.walk(<path>): in combination with abs_path = os.path.join(root, file). Calling imread afterwards, as in img = ocv.imread(abs_path) is always going to work.
In case no one mentioned in this question, another way to workaround is using plt to read image, then convert it to BGR format.
img=plt.imread(img_path)
print(img.shape)
img=img[...,::-1]
it has been mentioned in
cv2.imread does not read jpg files
This took a long time to resolve. first make sure that the file is in the directory and check that even though windows explorer says the file is "JPEG" it is actually "JPG". The first print statement is key to making sure that the file actually exists. I am a total beginner, so if the code sucks, so be it.
The code, just imports a picture and displays it . If the code finds the file, then True will be printed in the python window.
import cv2
import sys
import numpy as np
import os
image_path= "C:/python27/test_image.jpg"
print os.path.exists(image_path)
CV_LOAD_IMAGE_COLOR = 1 # set flag to 1 to give colour image
CV_LOAD_IMAGE_COLOR = 0 # set flag to 0 to give a grayscale one
img = cv2.imread(image_path,CV_LOAD_IMAGE_COLOR)
print img.shape
cv2.namedWindow('Display Window') ## create window for display
cv2.imshow('Display Window', img) ## Show image in the window
cv2.waitKey(0) ## Wait for keystroke
cv2.destroyAllWindows() ## Destroy all windows
I had a similar problem, changing the name of the image to English alphabetic worked for me. Also, it didn't work with a numeric name (e.g. 1.jpg).
My OS is Windows 10. I noticed imread is very sensitive to path. No any recommendation about slashes worked for me, so how I managed to solve problem: I have placed file to project folder and typed:
img = cv2.imread("MyImageName.jpg", 0)
So without any path and folder, just file name. And that worked for me.
Also try different files from different sources and of different formats
I spent some time on this only to find that this error is caused by a broken image file on my case. So please manually check your file to make sure it is valid and can be opened by common image viewers.
I had a similar issue,changing direction of slashes worked:
Change / to \
In my case helped changing file names to latin alphabet.
Instead of renaiming all files I wrote a simple wrapper to rename a file before the load into a random guid and right after the load rename it back.
import os
import uuid
import cv2
uid = str(uuid.uuid4())
def wrap_file_rename(my_path, function):
try:
directory = os.path.dirname(my_path)
new_full_name = os.path.join(directory, uid)
os.rename(my_path, new_full_name)
return function(new_full_name)
except Exception as error:
logger.error(error) # use your logger here
finally:
os.rename(new_full_name, my_path)
def my_image_read(my_path, param=None):
return wrap_file_rename(my_path, lambda p: cv2.imread(p) if param is None else cv2.imread(p, param))
Sometimes the file is corrupted. If it exists and cv2.imread returns None this may be the case.
Try opening the file כfrom file explorer and see if that works
I've run into this. Turns out the PIL module provides this functionality.
Similarly, numpy.imread and scipy.misc.imread both didn't exist until I installed PIL
In my configuration (win7 python2.7), that was done as follows:
cd /c/python27/scripts
easy_install PIL

Import file into python

I'm new to python and trying to learn a few exercises via colab. I want to import a CSV file that I saved to my desktop. Unfortunately, I keep getting a "cannot find file" error message. Not sure what I'm doing wrong.
Here's my code:
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
mpg = pd.read_csv(r"C:\Users\micha\OneDrive\Desktop\mpg2018.csv.csv")
I tried to change csv.csv to csv.txt or leave as just .csv but nothing works. Any help would be great!
Foward slashes will work in this function.
mpg = pd.read_csv("C:/Users/micha/OneDrive/Desktop/filename.csv")
Since you've imported "os", you could also use path.join()
p = os.path.join("C:\\", "Users", "micha", "OneDrive", "Desktop", "a.csv")
mpg = pd.read_csv(p)
Also, that file format repetition within the name seems unnecessary. It may lead to more confusion.
You are using colab.research.google.com, which lives in its own cloud world and has no idea of what files are on your personal machine. However, if you
from google.colab import files
files.upload()
It will open a nice dialog box which will allow you to find the file in the usual way.
In files section you find Upload button click on it add your file in colab
now simply import pd.read_csv(path)
how you find path: left click on csv file then select copy path and paste in place of path in pd.read_csv()

set directory for search program in python

I am trying to develop a CNN for image processing. I have about 130 gigs stored on a separate drive on my comp, and I'm having trouble navigating a simple python search program to search through that specified directory. Im trying to have it find a bunch of random XML files scattered in a host of sub-directories/sub-directories/subs on that drive. How do I specify for just this one python program the directory it should be searching in, keeping it only to the context of the program?
Ive tried setting a variable Path = "B:\\MainFolder\SubFolder" and using os.walk, but it makes it through the first directory then stops.
can you try the following:
import os
import glob
base_dir = 'your/start/sirectory'
req_files = glob.glob(os.path.join(base_dir, '**/*.xml'), recursive=True)
Jeril and Eduardo, thank you for the help. i took a shot at pathlib and it worked. idk what was up with my glob code, looked basically the same as yours Jeril:
import glob, os
filelist = []
from pathlib import Path
for path in Path('B:\\CTImageDataset\LIDC-IDRI').rglob('*.xml'):
filelist.append(path.name)
print(filelist)
Worked great, thanks again

How do I load a file with 'loadtxt ?'

Sorry for this beginner question, but...I'm a Python beginner. Still, I can't seem to find a proper answer for loadtxt not 'finding my file'...
import os
print(os.getcwd())
returns, I suppose, my current working directory.
In this case:C:\Users\danie\Desktop\python
So, when I place my csv file in it and run:
import numpy as np
dataset=np.loadtxt('Desktop/python/pima-indians-diabetes.csv', delimiter=",")
I still get
OSError: Desktop/python/pima-indians-diabetes.csv not found.
I have tried relative paths, absolute paths, f=open(..), paths with '/' and paths with '\' or with '\'...but nothing seems to make it work..
Any ideas ?
**RESOLVED: I tried Max L's hint: print(os.listdir(os.getcwd()))
and I saw the list of files in my current directory:...'pima-indians-diabetes.csv.csv' ....turns out I had put the csv extension on the file name myself **
If your working directory is C:\Users\danie\Desktop\python, that means that is where Python will start to look for files to import when using a relative path.
What is a relative path? It's the path to the file you want, relative to your current working directory. If a file is in the same directory, no prefix should be needed so it should just be
np.loadtxt('pima-indians-diabetes.csv', ...

Access data from the server in python

My teacher put up a large data in the school server and gave me a piece of code to open up the files. Below is my code:
import sys
sys.path.append("/Data/Data123/.local/lib/python2.7/site-packages")
from cloud.common import get_tile
from scipy.io import netcdf_file as copen
from scipy import interpolate
import matplotlib
from matplotlib import pyplot as pp
import matplotlib.cm as cm
import numpy
path = '/Data/a'
filenames = ['Hello.nc']
But when I run the code, it says there is "No such file or directory :'Hello.nc'
I am sure files are in that directory. So I want to ask, what did I do wrong?
Or am I not even collecting to the directory?
Thanks
It would be very difficult to answer this question without knowing what files are on the server and also looking at the code that actually connects, and attempts to retrieve the file; but I can provide you with this suggestion.
Use os.path instead of declaring a literal path string. For example:
Change:
path = '/Data/a'
To:
import os
path = os.path.join(r'/Data', 'a')
Then, when you concatenate path with a filename, use os.path.join again:
os.path.join(path, filenames[0]) # Modify to fit your filenames loop accordingly
The problem may be in the way you combine path with a filename. If this does not help, please add more code or double check the server to make sure the file is there.

Categories

Resources