import pprint as pp
original_img = cv2.imread("/content/drive/My Drive/images/image1.jpg") #here i want to use multiple images atleast 250 images.
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
results = tfnet2.return_predict(original_img)
print(results)
I guess all your images are in the folder images. So you can use os to gett all their filenames.
import os
pth = "/content/drive/My Drive/images" # make sure it is correct
images = os.listdir(pth)
for image in images:
image_path = os.path.join(pth, image)
original_img = cv2.imread(image_path)
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
results = tfnet2.return_predict(original_img)
print(results)
anyone can use for loop add empty folder to direct all the json files directly to the same folder using basic addition '+' operator.
for i in range():
original_img = cv2.imread("/folder path(500+ images)/" + any_empty_folder[i])
Related
I am trying to crop all images in a folder and save them in another folder. Then split all the images I have cropped using the image_slicer library.
I know a similar question like this has been asked but the difference is that I don't want the original folder to contain the cropped photos.
Here is my code so far; it runs but does nothing:
from PIL import Image
import image_slicer
import os
path = 'BeforeAfter'
arr = os.listdir(path)
def crop():
for i in arr:
if os.path.isfile(i):
img = Image.open(i)
f, e = os.path.splitext(i)
left = 66.6
top = 37.4
right = 1212.4
bottom = 550.7
imCrop = img.crop((left, top, right, bottom))
imCrop.save("CroppedImages/", "PNG", quality= 100)
# tiles = image_slicer.slice(toslice, 12, save=False)
# image_slicer.save_tiles(tiles, directory='frames')
crop()
I am programming a code that uses 30 images and I want to put those images in an array to resize them and then use them in other functions. I was trying some things but the second loop just shows me one unique image resized 30 times.
import cv2 as cv
import glob
import numpy as np
files = glob.glob ("C:/Users/Project/imgs/*.jpg")
images = np.empty(len(files))
#This loop reads images and show rgb images
#Works OK
for i in files:
#print(myFile)
images= cv.imread(i)
cv.imshow('myFile'+str(i),images)
new = []
for i in range(30):
new = cv.resize(images,(200,266))
cv.imshow('imagen', new)
cv.waitKey(0)
cv.destroyAllWindows()
If you want to keep many elements then first create empty list and next use apppend() to add element to list.
More or less
all_images = []
for name in files:
#print(name)
image = cv.imread(name)
cv.imshow('myFile '+name, image) # you don't need `str()`
all_images.append(image)
resized_images = []
for image in all_images:
new = cv.resize(image, (200,266))
cv.imshow('imagen', new)
resized_images.append(new)
If you want to resize only first 30 images
for image in all_images[:30]:
I have downloaded a dataset for a deep learning project that contains images (.png) and the corresponding label for each image (.txt). I have all the images' paths in a list x. I want to iterate through these paths, preprocess the images using cv2, and append the new images to a new list images_data. However, every time I try to loop through it, I keep getting this same error: cv2.error: OpenCV(4.1.1) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
Even when I comment out that line of code that throws the error, I get another error when trying to resize the image.
This is the for loop I'm using to iterate through the list:
images_data = []
for file in x:
img = cv2.imread(file)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (80, 80))
images_data.append(img)
My x list looks pretty much like this:
x = [car1.png, car2.png, car3.png, car4.png, car5.png]
How can I solve this error?
That error indicates your img variable is empty so cv2.imread(file) did not read an image. You can check this after reading the image and before converting the color or resizing, with a simple if case:
if img is None:
print('Error reading image')
else:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
or check if the file exists using the os module:
img = cv2.imread(file)
if os.path.isfile(file):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
os.path.isfile(file) will return True if the file exists.
I am assuming your files, car1.png, car2.png etc are in a different folder and not in the same path with this script in which case, you need to append the directory of the images to the file name before you can read it. So for example, if your images are in, let's say, '/home/Deep_Learning/Car_Images/' then when reading the images, the variable file must contain the string: /home/Deep_Learning/Car_Images/car1.png, for the first image and not just car1.png. You can do this using python's os module like this:
import cv2
import os
# Directory of the images. Change it according your path
data_dir = '/home/Deep_Learning/Car_Images/'
images_data = []
for file in x:
file_name = os.path.join(data_dir, file) # Append the image folder with the image name
if os.path.isfile(file_name) is False: #Check if image file exists
print("Image file ", file_name, "does not exist")
else:
img = cv2.imread(file_name)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (80, 80))
images_data.append(img)
I have about 200- 400 pictures in a folder to be processed. I am trying to use python to write a sort of script to process these images. The image output are changing but there are some logic error which i am aware of but no idea to amend. These are the two files i have so far
test2 and resize are 2 .py files that i have created. test2.py will be calling resize.py it will resize images that are in the directory
test2.py
import glob
import cv2
from resize import process
for image_file in glob.iglob('/home/winowa/Desktop/Intern101/fisherFace/test/*.jpg'):
process(image_file)
resize.py
import cv2
def process(filename):
image = cv2.imread(filename)
print image.shape
r = 100.0 / image.shape[1]
dim = (100, int(image.shape[0] *r))
imageresized = cv2.resize(image,(300,300),dim,interpolation = cv2.INTER_AREA)
for i in range(19):
cv2.imwrite( 'imageresized_{}.jpg'.format(i) ,imageresized )
print 'imageresized_{}.jpg'.format(i)
i am aware that after entering resize.py it will loop19 times before going to the 2nd round of test2.py. I am trying to correct the program to move on to the next image and will output images name as imageresized1.jpg,imageresized2.jpg and so on. Now images are the right name but wrong images. Only one image is being prcessed due to the for loop. range(19) are 19 images in my folder
What about
test2.py
import glob
import cv2
from resize import process
for (i,image_file) in enumerate(glob.iglob('/home/winowa/Desktop/Intern101/fisherFace/test/*.jpg')):
process(image_file, i)
resize.py
import cv2
def process(filename, key):
image = cv2.imread(filename)
print image.shape
r = 100.0 / image.shape[1]
dim = (100, int(image.shape[0] *r))
imageresized = cv2.resize(image,(300,300),dim,interpolation = cv2.INTER_AREA)
cv2.imwrite( 'imageresized_{}.jpg'.format(key) ,imageresized )
print 'imageresized_{}.jpg'.format(key)
This assumes that you only want to write a single file for each call to process and that your "19 files" will be the files matched by glob.
I am trying to open a set of images in python, but I am a bit puzzled on how I should do that. I know how to do it with one image, but I don't have a clue on how to handle several hundreds of images.
I have a file folder with a few hundred .jpg images. I want to load them in a python program to do machine learning on them. How can I do this properly?
I don't have any code yet since I am already struggling with this.
But my Idea in pseudocode was
dataset = load(images)
do some manipulations on it
How I have done it before:
from sklearn.svm import LinearSVC
from numpy import genfromtxt,savetxt
load = lambda x: genfromtxt(open(x,"r"),delimiter = ",",dtype = "f8")[1:]
dataset = load("train.csv")
train = [x[1:] for x in dataset]
target = [x[0] for x in dataset]
test = load("test.csv")
linear = LinearSVC()
linear.fit(train,target)
savetxt("digit2.csv",linear.predict(test),delimiter = ",", fmt = "%d")
Which worked fine because of the format. Al the data was in one file.
If you want to process each image individually (assuming you're using PIL or Pillow) then do so sequentially:
import os
from glob import glob
try:
# PIL
import Image
except ImportError:
# Pillow
from PIL import Image
def process_image(img_path):
print "Processing image: %s" % img_path
# Open the image
img = Image.open(img_path)
# Do your processing here
print img.info
# Not strictly necessary, but let's be explicit:
# Close the image
del img
images_dir = "/home/user/images"
if __name__ == "__main__":
# List all JPEG files in your directory
images_list = glob(os.path.join(images_dir, "*.jpg"))
for img_filename in images_list:
img_path = os.path.join(images_dir, img_filename)
process_image(img_path)
Read the documentation on python glob module and in a loop process each of the images in turn.