Reputation: 66
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'
Upvotes: 1
Views: 9309