I've been trying to merge some pictures to create a video, all of this using Opencv. But, the problem here is that Opencv does create the .avi file and it opens, using VLC Media Player, but when I'm trying to watch the video created, it shows nothing and doesn't show how long does the video last. However, the file size is around 6kb. There are 18 images and they have an average size os 252kb. I think that's too weird and incoherent.
Here's a look at my code:
import cv2
import os
frameSize = (500, 500)
with os.scandir('Taylor') as Taylor_Images:
for image in Taylor_Images:
print(image.name)
with os.scandir('Taylor_5') as Taylor5_Images:
for image in Taylor5_Images:
print(image.name)
image_Taylor = []
image_Taylor_5 = []
ext_2 = '.png'
adding = '_5'
path_2 = 'Taylor_5/'
ext = '.png'
path = 'Taylor/'
for i in range(1,10):
img_name = str(i) + ext
img = path + str(i) + ext
image_Taylor.append(img)
img_name_2 = str(i) + ext_2
img_2 = path_2 + str(i) + adding + ext_2
image_Taylor_5.append(img_2)
out = cv2.VideoWriter('output_video2.avi',cv2.VideoWriter_fourcc(*'DIVX'), 60, frameSize)
for i in range(0,9):
img = cv2.imread(image_Taylor[i])
out.write(img)
img_2 = cv2.imread(image_Taylor_5[i])
out.write(img_2)
out.release()
Update 1
As Vatsal suggested, I checked all the sizes of the images and I found that some of them didn't have the same size(Width,Height), so I resized them for having the same size(400,800).
With regard to what Tim said, the images do have that file size, I attach a picture of what I did according to your suggestion of making their file size a multiple of 4.
Checking the size of the images
This is the kind of pictures I'm using
However, the video generated from the script still has a size of 6kB.
Related
I've done a python script using Pillow to automatically watermark the images on one folder and save the watermarked image to other folder. The program is made but I noticed that the new photos come with some more MB like the original one is 10Mb and the watermarked is 25Mb and the program also takes a lot of time to run. I don't know what to do in order to improve it.
Here's the code
from PIL import Image
import os
#foreground = Image.open("watermark.png").convert('RGBA')
#background = Image.open("FotosAntes\\21231891_468587483512430_7958322633319552407_n.jpg").convert('RGBA')
#
#maxsize = (300,300)
#foreground.thumbnail(maxsize, Image.ANTIALIAS)
#
#background.paste(foreground, (670, 500), foreground)
#background.convert('P', palette=Image.ADAPTIVE, colors=256)
#background.save("FotosDepois\\Foto1.png", "PNG")
#
#background.show()
original_path = ("FotosAntes")
destination_path = ("FotosDepois")
#maxsize = (500,500)
foreground = Image.open("arroz.png").convert('RGBA')
#foreground.thumbnail(maxsize, Image.ANTIALIAS)
for (dirName, subDirs, fileNames) in os.walk(original_path):
for i in fileNames:
file_name_op = (os.path.splitext(i)[0])
background = Image.open(os.path.join(dirName, i)).convert('RGBA')
background.paste(foreground, (4550, 2850), foreground)
background.convert('P', palette=Image.ADAPTIVE, colors=256)
outfile = os.path.split
background.save("FotosDepois\\" + file_name_op + ".png")
print("Foto complete")
The first comments was the version of my program that I tested to do only one photo and then I created the final program (the loop).
I am trying to create a program that will resize any image in a directory to 299x299. Then, I want to rename that image and convert it to a jpeg, so that all of the images will be named 0.jpg, 1.jpg, 2.jpg, etc. I also want to move the converted files to their own directory.
I have already solved the resizing portion of it. However, when I added the code for renaming, i.e. (index = 0, new_image.save)file_name, str(index), + ".jpg", and index += 1), the resizing portion no longer works. Does anyone have any suggestions?
This is what I have so far:
#!usr/bin/python
from PIL import Image
import os, sys
directory = sys.argv[1]
for file_name in os.listdir(directory):
print ("Converting %s" % file_name + "...")
image = Image.open(os.path.join(directory, file_name))
size = 299, 299
image.thumbnail(size, Image.ANTIALIAS)
w, h = image.size
new_image = Image.new('RGBA', size, (255, 255, 255, 255))
new_image.paste(image, ((299 - w) / 2, (299 - h) / 2))
index = 0
new_image_file_name = os.path.join(directory, file_name)
new_image.save(file_name, str(index) + ".jpg")
index += 1
print ("Conversion process complete.")
From the documentation:
Image.save(fp, format=None, **params)
Saves this image under the given
filename. If no format is specified, the format to use is determined
from the filename extension, if possible.
The correct syntax for image.save is:
new_image.save(file_name, 'JPG')
To move a file, you can use shutil.move:
import shutil
shutil.move(file_name, 'full/path/to/dst/') # the second argument can be a directory
I already saw the examples suggested but some of them don't work.
So, I have this code which seems to work fine for one image:
im = Image.open('C:\\Users\\User\\Desktop\\Images\\2.jpg') # image extension *.png,*.jpg
new_width = 1200
new_height = 750
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save('C:\\Users\\User\\Desktop\\resized.tif') # .jpg is deprecated and raise error....
How can I iterate it and resize more than one image ? Aspect ration need to be maintained.
Thank you
# Resize all images in a directory to half the size.
#
# Save on a new file with the same name but with "small_" prefix
# on high quality jpeg format.
#
# If the script is in /images/ and the files are in /images/2012-1-1-pics
# call with: python resize.py 2012-1-1-pics
import Image
import os
import sys
directory = sys.argv[1]
for file_name in os.listdir(directory):
print("Processing %s" % file_name)
image = Image.open(os.path.join(directory, file_name))
x,y = image.size
new_dimensions = (x/2, y/2) #dimension set here
output = image.resize(new_dimensions, Image.ANTIALIAS)
output_file_name = os.path.join(directory, "small_" + file_name)
output.save(output_file_name, "JPEG", quality = 95)
print("All done")
Where it says
new_dimensions = (x/2, y/2)
You can set any dimension value you want
for example, if you want 300x300, then change the code like the code line below
new_dimensions = (300, 300)
I assume that you want to iterate over images in a specific folder.
You can do this:
import os
from datetime import datetime
for image_file_name in os.listdir('C:\\Users\\User\\Desktop\\Images\\'):
if image_file_name.endswith(".tif"):
now = datetime.now().strftime('%Y%m%d-%H%M%S-%f')
im = Image.open('C:\\Users\\User\\Desktop\\Images\\'+image_file_name)
new_width = 1282
new_height = 797
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save('C:\\Users\\User\\Desktop\\test_resize\\resized' + now + '.tif')
datetime.now() is just added to make the image names unique. It is just a hack that came to my mind first. You can do something else. This is needed in order not to override each other.
I assume that you have a list of images in some folder and you to resize all of them
from PIL import Image
import os
source_folder = 'path/to/where/your/images/are/located/'
destination_folder = 'path/to/where/you/want/to/save/your/images/after/resizing/'
directory = os.listdir(source_folder)
for item in directory:
img = Image.open(source_folder + item)
imgResize = img.resize((new_image_width, new_image_height), Image.ANTIALIAS)
imgResize.save(destination_folder + item[:-4] +'.tif', quality = 90)
I am using the following code to read multiple images from a folder and to take a specific crop from all of them and also write them at the end. The cropping part does not seem to work meaning the cropped parts are not getting written.
# import the necessary packages
import cv2
import os, os.path
#image path and valid extensions
imageDir = "C:\\Users\\Sayak\\Desktop\\Training\\eye\\1" #specify your path here
image_path_list = []
valid_image_extensions = [".jpg", ".jpeg", ".png", ".tif", ".tiff"] #specify your vald extensions here
valid_image_extensions = [item.lower() for item in valid_image_extensions]
#create a list all files in directory and
#append files with a vaild extention to image_path_list
for file in os.listdir(imageDir):
extension = os.path.splitext(file)[1]
if extension.lower() not in valid_image_extensions:
continue
image_path_list.append(os.path.join(imageDir, file))
#loop through image_path_list to open each image
for imagePath in image_path_list:
image = cv2.imread(imagePath)
# display the image on screen with imshow()
# after checking that it loaded
if image is not None:
cv2.imshow(imagePath, image)
elif image is None:
print ("Error loading: " + imagePath)
#end this loop iteration and move on to next image
continue
crop_img = image[200:400, 100:300]
cv2.imwrite('pic{:>05}.jpg'.format(imagePath), crop_img)
# wait time in milliseconds
# this is required to show the image
# 0 = wait indefinitely
# exit when escape key is pressed
key = cv2.waitKey(0)
if key == 27: # escape
break
# close any open windows
cv2.destroyAllWindows()
I have modified your code posted above. The problem lies with your string formatting used in cv2.imwrite(). The first argument must be an absolute path to where the file should be saved, but your code is passing in something like this.
pic{:>05}.jpg => pic/home/ubuntu/Downloads/10_page.png.jpg. When I used a valid file name there is no problem saving the cropped image at all.
#loop through image_path_list to open each image
for i,imagePath in enumerate(image_path_list):
image = cv2.imread(imagePath)
# display the image on screen with imshow()
# after checking that it loaded
if image is not None:
cv2.imshow(imagePath, image)
elif image is None:
print ("Error loading: " + imagePath)
#end this loop iteration and move on to next image
continue
# Please check if the size of original image is larger than the pixels you are trying to crop.
(height, width, channels) = image.shape
if height >= 400 and width >= 300:
plt.imshow(image)
plt.title('Original')
plt.show()
crop_img = image[100:400, 100:400]
# Problem lies with this path. Ambiguous like pic/home/ubuntu/Downloads/10_page.png.jpg
print('pic{:>05}.jpg'.format(imagePath))
# Try a proper path. A dirname + file_name.extension as below, you will have no problem saving.
new_image = os.path.join(imageDir,'{}.png'.format(str(i)))
cv2.imwrite(new_image, crop_img)
plt.imshow(crop_img)
plt.title('Cropped')
plt.show()
I have such a loop to write video files from images:
for a in range(len(events)):
c_videos = []
first = events[a][0]
last = events[a][1]
c_videos = video_ids[numpy.where(numpy.logical_and(timestamps >= first, timestamps <= last))]
video_name = "/export/students/sait/9-may-video-dataset/video-" + str(events[a][2]) + ".avi"
video = cv2.VideoWriter(video_name,-1,1,(width,height))
for b in range(len(c_videos)):
img_file = "/export/students/sait/9-may-results/rgb-" + str(c_videos[b]) + ".ppm"
img = cv2.imread(img_file)
video.write(img)
cv2.destroyAllWindows()
video.release()
But I cannot become successful in creating videos. I don't see any created video file under the destination directory.
How can I fix this problem?