Luke Johnston
Luke Johnston

Reputation: 33

Converting code to read files in windows to linux

I'm currently getting an error from cv2 resize which is indicating that there is nothing in the file. It works fine on windows but I'm struggling to work out what needs to be done (apart from a change in the path name) for it to work on linux.

path1 ='C:/Users/L/Software/Data/channels/ch3'

listing = os.listdir(path1)

ch3_matrix = array([array(cv2.resize(cv2.imread(path1 + '\\' + im2,0),(55,55))).flatten()
            for im2 in listing])

Upvotes: 0

Views: 48

Answers (1)

linusg
linusg

Reputation: 6439

The problem is the final path you're building:

path1 + '\\' + im2

where path1 is your base directory and im2 the image filename. Doing it like this (with string concatenation) can lead to problems very fast and is generally discouraged.

I would recommend using os.path.join or the newer pathlib module for this, which both work platform-independent:

import os

BASE_PATH = 'C:/Users/L/Software/Data/channels/ch3'

images = os.listdir(BASE_PATH)
ch3_matrix = array([
    array(cv2.resize(cv2.imread(os.path.join(BASE_PATH, image), 0), (55, 55))).flatten()
    for image in images
])

or

import pathlib

BASE_PATH = pathlib.Path('C:/Users/L/Software/Data/channels/ch3')

images = os.listdir(BASE_PATH)
ch3_matrix = array([
    array(cv2.resize(cv2.imread(str(BASE_PATH / image), 0), (55, 55))).flatten()
    for image in images
])

For your code to work on Linux you will only have to change the BASE_PATH.

Upvotes: 1

Related Questions