I am trying to segment images based on their label tag as helmet, non-helmet or unprocessed images for my project. But there is error saying image object is null. I have already made a secondary script where I processed over the same image which is working.I don't know why but it seems opencv library is unable to read one particular image. Any help will be really appreciated.
import requests
import shutil
import json
import sys
import os
import cv2
x=0
lis=[]
s=""
def batwara(filename,data):
print("unproccesed/"+filename[6:])
print(data)
image = cv2.imread(filename)
if image is None:
print("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN")
return
color = (255, 0, 0)
thickness = 2
totfaces = data['annotation']
if totfaces is None:
cv2.imwrite("unproccesed/"+filename[6:],image)
return
x=0
for face in totfaces:
x=x+1
new_file=str(x)+filename[9:]
print(new_file)
label= face['label']
print ("label=============",label)
wid=face['imageWidth']
hei=face['imageHeight']
x1=int(face['points'][0]['x']*wid)
y1=int(face['points'][0]['y']*hei)
x2=int(face['points'][1]['x']*wid)
y2=int(face['points'][1]['y']*hei)
#print (x1,y1,x2,y2,wid,hei)
start_point = (x1, y1)
end_point = (x2, y2)
crop_img = image[y1:y2, x1:x2]
if len(label)==0:
new_file= "unidentified/img"+new_file
cv2.imwrite(new_file,crop_img)
elif label[0] == "Without Helmet":
new_file= "non_helmet/img"+new_file
cv2.imwrite(new_file,crop_img)
elif label[0] == "With Helmet":
new_file= "helmet/img"+new_file
cv2.imwrite(new_file,crop_img)
with open('/home/oem/Downloads/Bikers Wearing Helmet Or Not.json') as f:
while True:
c = f.read(1)
s=s+c
if c=='{' or c=='[':
lis.append(c)
if c==']'or c=='}':
lis.pop()
if len(lis)==0:
x=x+1
#print(filename)
#print(s)
data = json.loads(s)
filen,ex= os.path.splitext(data['content'])
filename= "image/img"+str(x)+ex
#print(data)
#print (data['content'])
# This is the image url.
image_url = data['content']
# Open the url image, set stream to True, this will return the stream content.
resp = requests.get(image_url, stream=True)
# Open a local file with wb ( write binary ) permission.
local_file = open(filename, 'wb')
# Set decode_content value to True, otherwise the downloaded image file's size will be zero.
resp.raw.decode_content = True
# Copy the response stream raw data to local image file.
shutil.copyfileobj(resp.raw, local_file)
# Remove the image url response object.
del resp
if ex!=".png":
batwara(filename,data)
s=""
if not c:
print ("End of file")
print(x)
break
The error displayed on the terminal is:
Traceback (most recent call last):
File "app2.py", line 91, in <module>
batwara(filename,data)
File "app2.py", line 46, in batwara
cv2.imwrite(new_file,crop_img)
cv2.error: OpenCV(4.2.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:715: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'
You need to make sure that x1 == x2 or y1 == y2
Related
I been trying working in a program that crop some parts of a frame in a video with opencv.
the first program works, but when i try to resize the cropped images at some point crash giving me this error:
cv2.error: OpenCV(4.5.2) /tmp/pip-req-build-eirhwqtr/opencv/modules/imgcodecs/src/loadsave.cpp:721: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'
i read that i could be an error of windows, but i try it in Ubuntu and its was the same result, the program pick the data from a csv that saves [frame, x, y]
All its in the main(path, lent) function!
import os
import cv2
import csv
video_path = ''
rl = 0
label = 1
def main(path, lent):
global video_path
global rl
global label
rl = lent
frames = []
coord = []
with open(path, "r") as data:
reader = csv.reader(data, delimiter=',')
for idx, row in enumerate(reader):
if idx == 0:
video_path = row[0]
else:
frames.append(float(row[0]))
coord.append((int(row[1]), int(row[2])))
video = cv2.VideoCapture(video_path)
if not video.isOpened():
print("Error! No file found!")
i = 0
while i < len(frames):
video.set(1, frames[i])
ret, frame = video.read()
img_resized = frame
if not os.path.exists(f"src/data/{video_path[-10:-4]}/resized{rl}"):
os.makedirs(f"src/data/{video_path[-10:-4]}/resized{rl}")
else:
print(i)
img_resized = img_resized[(coord[i][1] - rl):(coord[i][1] + rl), (coord[i][0] - rl):(coord[i][0] + rl)]
cv2.imwrite(f"src/data/{video_path[-10:-4]}/resized{rl}/frame{i}.jpg", img_resized)
i += 1
print("Success!")
video.release()
thanks for the help!
I'm creating a plot in R, but then trying to return the resulting image data to Python so that Python can display the image.
Within R, I've used the magick library to hold the image in memory (instead of plotting to the screen).
"We use image_write to export an image in any format to a file on disk, or in memory if path = NULL"
I'm unsure how to process either the SexpExtPtr or ByteVector types that are returned by rpy2 to Python.
import rpy2.robjects as ro
r = ro.r
r('''
library("magick")
figure <- image_graph(width = 400, height = 400, res = 96)
plot(c(1,2,3))
image <- image_write(figure, path = NULL, format = "png")
# image_write(figure, path = 'example.png', format = 'png')
''')
figure = ro.globalenv['figure']
image = ro.globalenv['image']
im = Image.open(BytesIO(image))
The code above gives me the error:
Traceback (most recent call last):
File "stackoverflow.py", line 23, in <module>
im = Image.open(BytesIO(image))
TypeError: a bytes-like object is required, not 'ByteVector'
In Python:
figure has type <class 'rpy2.rinterface.SexpExtPtr'>
image has type <class 'rpy2.robjects.vectors.ByteVector'>
So... it turns out that <class 'rpy2.robjects.vectors.ByteVector'> is an iterable and I can use bytes() to construct an array of bytes.
Also, by putting the code inside a function that uses return to return the PIL image I can get the image to display within a Jupyter notebook (alternatively we could just do image.show())
from io import BytesIO
import PIL.Image as Image
import rpy2.robjects as ro
def main():
r = ro.r
r('''
library("magick")
figure <- image_graph(width = 400, height = 400, res = 96)
plot(c(1,2,3))
image <- image_write(figure, path = NULL, format = "png")
image_write(figure, path = 'example.png', format = 'png')
''')
image_data = ro.globalenv['image']
image = Image.open(BytesIO(bytes(image_data)))
return image
if __name__ == '__main__':
image = main()
image.show()
I just want Help with my code because I can't make it work properly.
The part where I am struggling is when the image is being resized to 300x300.
When I upload an image less than 300x300 it works like a charm, but when the image needs to be resized it shows that :
Traceback (most recent call last):
File "C:\Users\KAYL\Documents\Python\ASCII\ascii.py", line 20, in <module>
value = image_nb.getpixel((x, y))
File "C:\Users\KAYL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\Image.py", line 1315, in getpixel
return self.im.getpixel(xy)
IndexError: image index out of range
I just want the variable image_original to be resized and saved to image
Here's my code :
import io
import easygui
from resizeimage import resizeimage
import webbrowser
image_path = easygui.fileopenbox()
image_original = Image.open(image_path)
largeur, hauteur = image_original.size
image = resizeimage.resize_thumbnail(image_original, [300, 300])
output = io.StringIO()
image_nb = image.convert('L')
for y in range(hauteur):
for x in range(largeur):
value = image_nb.getpixel((x, y))
if value < 64:
output.write('#')
elif value < 128:
output.write('#')
elif value < 192:
output.write('/')
else :
output.write(',')
output.write('\n')
with open('image finale.txt', mode='w') as f:
print(output.getvalue(), file=f)
webbrowser.open("image finale.txt")
I have been attempting to produce an OCR tool following this tutorial on youtube, and using the following script:
import os
import sys
import cv2
import numpy as np
input_f = 'letter.data'
img_resize_factor = 12
start, end = 6, -1
height, width = 16, 8
with open(input_f, 'r') as f:
for line in f.readlines():
data = np.array([255*float(x) for x in line.split('\t')[start:end]])
img = np.reshape(data, (height, width))
img_scaled = cv2.resize(img, None, fx=img_resize_factor, fy=img_resize_factor)
print(line)
cv2.imshow('img', img_scaled)
c = cv2.waitKey()
if c == 27:
break
The code falls over when attempting to use cv2.imshow('img', img_scaled) the window appears however is non responding and the image is not loaded into it.
I am using the most up to date version of OpenCV, I am running this in VisualStudio, and have had to add "python.linting.pylintArgs": ["--extension-pkg-whitelist=cv2"] to the user settings.
The error I get is:
Exception has occurred: cv2.error OpenCV(4.0.0)
c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:261:
error: (-2:Unspecified error) in function '__cdecl
cv::CvtHelper,struct cv::Set<3,4,-1>,struct
cv::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class
cv::_OutputArray &,int)' > Unsupported depth of input image: >
'VDepth::contains(depth)' > where > 'depth' is 6 (CV_64F) File
"C:\Users\aofarrell\Desktop\Python\NeuralNetworks\SimpleOCR.py", line
23, in
break
Everything in your script is wrong.
Solution
1) If you are opening a file, open just file, get data and get out of with statement
2) The error you are experiencing is due to wrong shape
I opened the file and extracted images
import os
import sys
import cv2
import numpy as np
input_f = 'letter.data'
start, end = 6, -1
def file_opener(input_f):
with open(input_f,'r') as fl:
for line in fl.readlines():
yield np.array([255*float(x) for x in line.split('\t')[start:-1]])
iterator = file_opener(input_f)
images = np.array([row for row in iterator]).reshape(52152,16,8) # array with 52152 images
for image_index in range(images.shape[0]):
IMAGE = cv2.resize(images[image_index,:],(0,0),fx=5,fy=5)
cv2.imshow('image {}/{}'.format(image_index,images.shape[0]),IMAGE)
cv2.waitKey(0)
cv2.destroyAllWindows(0)
I am trying to do simple crops of the images. Here is the code
from PIL.Image import Image
def get_image_half(image, half="upper"):
if half not in ["upper", "lower", "right", "left"]:
raise Exception('Not a valid image half')
img = Image.open(image)
width, height = img.size
if half == "upper":
return img.crop(0, 0, width, height//2)
elif half == "lower":
return img.crop(0, height//2, width, height)
elif half == "left":
return img.crop(0, 0, width//2, height)
else:
return img.crop(width//2, 0, width, height)
def get_image_quadrant(image, quadrant=1):
if not (1 <= quadrant <= 4):
raise Exception("Not a valid quadrant")
img = Image.open(image)
width, height = img.size
if quadrant == 2:
return img.crop(0, 0, width//2, height//2)
elif quadrant == 1:
return img.crop(width//2, 0, width, height//2)
elif quadrant == 3:
return img.crop(0, height//2, width//2, height)
else:
return img.crop(width//2, height//2, width, height)
# test code for the functions
if __name__ == "__main__":
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
file = os.path.join(dir_path,"nsuman.jpeg")
image = Image.open(file)
for i in ["upper", "lower", "left", "right"]:
get_image_half(image, i).show()
for i in range(1,5):
get_image_quadrant(image, quadrant=i)
I am getting following error.
image = Image.open(file)
AttributeError: type object 'Image' has no attribute 'open'
Quick googling led me to this link and I changed the import to
import PIL.Image
and changed code to
PIL.Image.open(image)
which gave another error
Traceback (most recent call last):
File "quadrant.py", line 53, in <module>
get_image_half(image, i).show()
File "quadrant.py", line 10, in get_image_half
img = Image.open(image)
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2557, in open
prefix = fp.read(16)
AttributeError: 'JpegImageFile' object has no attribute 'read'
The question here is how to resolve these errors and more importantly what are PIL.Image and PIL.Image.Image and what is the correct way to use them?
PIL.Image should open a file type object. Once opened, then you'll have a PIL.Image.Image object:
from PIL import Image
image = Image.open('/foo/myfile.png')
open(fp, mode='r')
Opens and identifies the given image file.
This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the PIL.Image.Image.load method). See PIL.Image.new.
fp: A filename (string), pathlib.Path object, or a file object. The file object must implement file.read, file.seek, and file.tell methods, and be opened in binary mode.
returns: a PIL.Image.Image object.