How to link images pr file in Google Colab - python

I failed to show the image,
below the code,
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import cv2
import os
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import RMSprop
img= image.load_img("cnn_happy_notHappy/traing/happy/1.png")
Error:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-13-2c0e7bdac5f8> in <module>()
----> 1 img= image.load_img("cnn_happy_notHappy/traing/happy/1.png")
1 frames
/usr/local/lib/python3.6/dist-packages/keras_preprocessing/image/utils.py in load_img(path, grayscale, color_mode, target_size, interpolation)
111 raise ImportError('Could not import PIL.Image. '
112 'The use of `load_img` requires PIL.')
--> 113 with open(path, 'rb') as f:
114 img = pil_image.open(io.BytesIO(f.read()))
115 if color_mode == 'grayscale':
FileNotFoundError: [Errno 2] No such file or directory: 'cnn_happy_notHappy/traing/happy/1.png'
The folder screenshots where image folder and file have,
Please help me to solve this issue,

You can import your images first in google colab then assign it to your img variable.
# you can run this in first cell
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import cv2
import os
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import RMSprop
# you can run this is the second cell will show a button to upload the file in google collab
from google.colab import files
uploaded = files.upload()
# use this after image in uploaded in the previous cell successfullt
img= image.load_img("1.png")

Related

No such file or directory: './dataset/time_series_covid19_confirmed_global.csv'

from google.colab import drive
drive.mount('/content/drive')
%cd /content/drive/MyDrive/AIP
[Errno 2] No such file or directory: '/content/drive/MyDrive/AIP' /content/drive/My Drive/Colab Notebooks
import os
import os.path
import requests
from scipy.integrate import odeint
import torch
from torch import nn, optim
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from pylab import rcParams
from pandas.plotting import register_matplotlib_converters
from sklearn.preprocessing import MinMaxScaler, StandardScaler
%matplotlib inline
%config InlineBackend.figure_format='retina'
sns.set(style='whitegrid',font_scale=0.6)
rcParams['figure.figsize'] = 6,4
register_matplotlib_converters()
# DATA
URL = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/"
CONFIRMED="time_series_covid19_confirmed_global.csv"
DEATH="time_series_covid19_deaths_global.csv"
RECOVERED="time_series_covid19_recovered_global.csv"
# Fixed random seed
RANDOM_SEED = 42 np.random.seed(RANDOM_SEED) torch.manual_seed(RANDOM_SEED)
# Download dataset from GitHub which was provided by the Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE).
if not os.path.isfile(f"./dataset/{CONFIRMED}"):
for name in [CONFIRMED, DEATH, RECOVERED]:
url = os.path.join(URL, name)
r = requests.get(url)
file_csv = open(os.path.join("./dataset", name), 'wb')
file_csv.write(r.content)
file_csv.close()
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-14-d47d8c7d4415> in <module>()
4 url = os.path.join(URL, name)
5 r = requests.get(url)
----> 6 file_csv = open(os.path.join("./dataset", name), 'wb')
7 file_csv.write(r.content)
8 file_csv.close()
FileNotFoundError: [Errno 2] No such file or directory: './dataset/time_series_covid19_confirmed_global.csv'
I have trying to run this code but I have some problem please can someone help me to solve this
How can I solve this problem in google collab ??????
also how to correct this problem No such file or directory: '/content/drive/MyDrive/AIP' /content/drive/My Drive/Colab Notebooks
Add content to path
file_csv = open(os.path.join("/content/dataset", name), 'wb')
Also check this file repository to check if your data is well downloaded in content file

Why i am getting "name 'os' is not defined" error?

Why i am getting this error? it should be work.Probally i'm missing something from my sight.
Before that same thing happen the for Classes.I tried rewrite and still same.
import tensorflow as tf
import cv2
import os
import matplotlib.pyplot as plt
import numpy as np
img_array = cv2.imread("Training/0/Training_233976.jpg")
img_array.shape
plt.imshow(img_array)
Datadirectory = "Training/"
Classes = ["0","1","2","3","4","5","6"]
for category in Classes:
path = os.path.join(Datadirectory, category)
for img in os.listdir(path):
img_array = cv2.imread(os.path.join(path,img))
plt.imshow(cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB))
plt.show()
break
break
I am formalizing in an answer, all you need to do is add a line at the top
import os
import os
use this at beginning of your code or where you are importing other libraries and codes .

How to put an image from s3 bucket to Python list

How can I put images from s3 bucket to Python list?
I am trying to convert an image from s3 bucket to img array like
from keras.layers import Conv2D, Conv2DTranspose, UpSampling2D
from keras.layers import Activation, Dense, Dropout, Flatten, InputLayer
from keras.layers.normalization import BatchNormalization
from keras.callbacks import TensorBoard
from keras.models import Sequential
from keras.models import model_from_json
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from skimage.color import rgb2lab, lab2rgb, rgb2gray
from skimage.io import imsave
import numpy as np
import os
import random
import tensorflow as tf
# Get images
import boto.s3.connection
conn = boto.s3.connect_to_region('us-east-2',
aws_access_key_id='mykey',
aws_secret_access_key='mysecretkey',
calling_format = boto.s3.connection.OrdinaryCallingFormat(),
)
bucket = conn.get_bucket('datasettrainimage123')
X = []
for filename in bucket.list():
X.append(img_to_array(load_img(filename.key.split('/')[-1])))
X = np.array(X, dtype = float)
I end up getting this error
No such file or directory: '02_0004.jpg'
Instead of boto its better to use boto3 as it is current. In boto3 there is download_file which will allow you download an image from s3 into your local storage. Once yo do this, you can read it in using load_img.

unable to view jpeg file

I was trying to view a jpeg file using the codes that I found online.
Here is the codes:
from PIL import Image
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
image = Image.open('/kaggle/input/chest-xray-pneumonia/chest_xray/__MACOSX/chest_xray/test/PNEUMONIA/._person121_bacteria_576.jpeg')
image.show()
But I get this error:
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-1-637f422434fd> in <module>
19
20
---> 21 image = Image.open('/kaggle/input/chest-xray-pneumonia/chest_xray/__MACOSX/chest_xray/test/PNEUMONIA/._person121_bacteria_576.jpeg')
22 image.show()
/opt/conda/lib/python3.6/site-packages/PIL/Image.py in open(fp, mode)
2685 warnings.warn(message)
2686 raise IOError("cannot identify image file %r"
-> 2687 % (filename if filename else fp))
2688
2689 #
OSError: cannot identify image file '/kaggle/input/chest-xray-pneumonia/chest_xray/__MACOSX/chest_xray/test/PNEUMONIA/._person121_bacteria_576.jpeg'
I'm wondering if this is an issue because I didn't load the data or something else?
I wrote nothing else on the notebook on the Kagglenotebook with the dataset: https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia
I usually name my files '.jpg' when using the PIL module and will then reference the appropriate file path.
I tried your code with a renamed image.jpg file and it worked fine, when I use '.jpeg' I get a similar error.
from PIL import Image
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
image = Image.open('/Users/GameComputerC/ocr3.jpg')
image.show()
Let me know if it works for you. That might only be part of the error.

Can not save file using the below python code. Error: numpy.ndarray object has no attribute 'save'

import os
import sys
import numpy as np
import scipy
import pylab
import pymorph
import mahotas
import matplotlib.pyplot as plt
import Image
from scipy import ndimage
from pymorph import regmax
from PIL import Image
path='all_images'
for file in os.listdir(path):
current = os.path.join(path, file)
extension = os.path.splitext(current)[-1]
fileType = extension.upper()
print(current)
if os.path.isfile(current):
img = mahotas.imread(current)
imgf = ndimage.gaussian_filter(img, 8)
pylab.gray()
imgf.save('dnaa.gif')
Can not save file using the below python code. Error: numpy.ndarray object has no attribute 'save'. Can anyone help how to save file using pylab. I guss the last line of the code has some issue.
Use mahotas.imsave('dnaa.gif', imgf) instead. The NumPy array you get from gaussian_filter doesn't have save functionality built in.

Categories