How to insert image into sqlite3 database? - python

Here is part of my code:
import sqlite3
import tkinter
import time
import PIL.Image, PIL.ImageTk
from PIL import Image,ImageTk
import cv2
import numpy as np
from tkinter import Tk, Label, Button, Entry, Toplevel
r=Tk()
conn = sqlite3.connect('datastorage.db')
print("Opened database successfully");
def snapshot(self):
# Get a frame from the video source
ret, frame = self.vid.get_frame()
I am capturing a frame from video and I need to insert it into a database which contains a text column and a blob(Binary Large Object) column. There are other similar questions which suggest converting to string and storing but since I already have images in blob format stored and I am extracting them using decode as seen in the code below, I need to store blob only.
blob_data=row[1]
nparr = np.frombuffer(blob_data, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
image1=cv2.resize(img_np,(260,200))
#cv2.imshow("data",image1)
#break
#Rearrang the color channel
b,g,r = cv2.split(image1)
image1 = cv2.merge((r,g,b))
hsv1=cv2.cvtColor(image1, cv2.COLOR_RGB2HSV)
kernel2 = np.ones((3,3),np.uint8)
I tried using the following query:
cursor=conn.execute("create table if not exists user_6 (id text, img blob)")
cursor=conn.execute("insert into user_6 values (?,?)",(ins,sqlite3.Binary(frame)))
but I am unable to display it using the same method I used to display all the other entries. The code used to display is the 2nd code block. I am encountering an error as shown:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\ABC\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\ABC\Desktop\Python tut\gui databse.py", line 71, in display
image1=cv2.resize(img_np,(130,100))
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:4045: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'
Can anyone help me out?

I was able to do it using the following code:
img_str = cv2.imencode('.jpg', frame)[1].tostring()
cursor=conn.execute("create table if not exists user_6 (id text, img blob)")
cursor=conn.execute("insert into user_6 values (?,?)",(ins,img_str))
conn.commit()
Although the colors in the image are different from the captured image.

Related

Insert and Display image from database using python

import mysql.connector
import base64
import io
from base64 import b64decode
from PIL import Image
import PIL.Image
with open('assets\zoha.jpeg', 'rb') as f:
photo = f.read()
encodestring = base64.b64encode(photo)
db=
mysql.connector.connect(user="root",password="",
host="localhost",database="pythonfacedetection")
mycursor=db.cursor()
sql = "INSERT INTO image(img) VALUES(%s)"
mycursor.execute(sql,(encodestring,))
db.commit()
sql1="select img from image where id=75"
mycursor.execute(sql1)
data = mycursor.fetchall()
image=data[0][0]
img = base64.b64decode(str(image))
img2=io.BytesIO(img )
img3= Image.open(img2)
img.show()
db.close()
I want to save my photo in database and display that photo from the database. The data has save on the database properly but can not display. I tried a lot but every time this error shows. Please advise me how can I solve this.
Traceback (most recent call last):
File "C:/Users/MDSHADMANZOHA/PycharmProjects/ImageFromDatabase/main.py", line 28, in
<module>
img3= Image.open(img2)
File "C:\Users\MDSHADMANZOHA\PycharmProjects\ImageFromDatabase\venv\lib\site-
packages\PIL\Image.py", line 3009, in open
"cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at
0x0000020247DCE308>

What is the data format read by the function cv2.imread? Working with tkinter and python

Good day, I am quite new to Python programming and I was tasked to do my own GUI with image inside my GUI. I have been doing some good progress but i was stuck when I want to insert an image into my GUI from my webcam. However, I did manage to get an image from the webcam but it has to be a different window with the GUI window.
In my GUI codes, it includes a simple code like this:
(I use range i<25 because my webcam needs warming up)
for i in range (25):
_ , frame = cap.read()
frame = cv2.flip(frame, 1)
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
i+=1
cv2.imshow("Latex Truck", cv2image)
img = cv2image
label = Label(root, image = img)
label.place(x = 300, y = 300)
Now, the problem is this. I successfully obtain the frame that I need and was able to show thanks to cv2.imshow but when I try to use the same source which is the "cv2image" in tkinter, it shows this error.
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "C:\Users\FF7_C\OneDrive\Desktop\Logo.py", line 82, in Capture
label = Label(root, image = img)
File "C:\Python34\lib\tkinter\__init__.py", line 2573, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2091, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "[[[ 49 32 22 255]
Now, logically I think I did what I needed to do which is the extract an image from the webcam which I did, the only problem now is I need to understand why tkinter cannot read the same information read by cv2.imshow.
Can someone guide me on this? Thank you very much! :)
The format returned by cv2.cvtColor(...) is of type numpy.ndarray. You need to convert it to format recognized by tkinter by using Pillow module:
from tkinter import *
from PIL import Image, ImageTk
import cv2
root = Tk()
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
# convert to image format recognized by tkinter
img = Image.fromarray(img)
tkimg = ImageTk.PhotoImage(image=img)
Label(root, image=tkimg).pack()
root.mainloop()

opencv error cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale

I am following a tutorial for face recognition using python. so this is the code im using
import cv2,os
import numpy as np
from PIL import Image
recognizer = cv2.face.createLBPHFaceRecognizer()
detector= cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
def getImagesAndLabels(path):
#get the path of all the files in the folder
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#create empth face list
faceSamples=[]
#create empty ID list
Ids=[]
#now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
#loading the image and converting it to gray scale
pilImage=Image.open(imagePath).convert('L')
#Now we are converting the PIL image into numpy array
imageNp=np.array(pilImage,'uint8')
#getting the Id from the image
Id=int(os.path.split(imagePath)[-1].split(".")[1])
# extract the face from the training image sample
faces=detector.detectMultiScale(imageNp)
#If a face is there then append that in the list as well as Id of it
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
Ids.append(Id)
return faceSamples,Ids
faces,Ids = getImagesAndLabels('trainingImage')
recognizer.train(faces, np.array(Ids))
recognizer.save('trainer/trainer.yml')
and this is the error message im getting
Traceback (most recent call last):
File "/home/pi/pythonpy/videofacedet/craft/codacus/trainer.py", line 32, in
faces,Ids = getImagesAndLabels('trainingImage')
File "/home/pi/pythonpy/videofacedet/craft/codacus/trainer.py", line 24, in getImagesAndLabels
faces=detector.detectMultiScale(imageNp)
error: /home/pi/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale
I read somewhere said that the folder I am pointing to (trainingImage) is empty, but it is not. I put my face training images there with the same filename format used by the tutorial author. I wish some one would help me with this problem.
problem solved. i had my haarcascade xml path wrong. fixed the path,and it is working as expected.

how to display PIL image with pygame?

I am trying to do some video stream from my raspberry pi over the wifi. I used pygame, because i also have to use gamepad in my project. Unfortunately I stucked on displaying received frame. Shortly: i get jpeg frame, open it with PIL, convert to string - after that i can load image from string
image_stream = io.BytesIO()
...
frame_1 = Image.open(image_stream)
f = StringIO.StringIO()
frame_1.save(f, "JPEG")
data = f.getvalue()
frame = pygame.image.fromstring(frame_1,image_len,"RGB")
screen.fill(white)
screen.blit(frame, (0,0))
pygame.display.flip()
and error is :
Traceback (most recent call last):
File "C:\Users\defau_000\Desktop\server.py", line 57, in <module>
frame = pygame.image.fromstring(frame_1,image_len,"RGB")
TypeError: must be str, not instance
Sloth's answer is incorrect for newer versions of Pygame. The tostring() definition is deprecated. Here is a working variant for Python 3.6, PIL 5.1.0, Pygame 1.9.3:
raw_str = frame_1.tobytes("raw", 'RGBA')
pygame_surface = pygame.image.fromstring(raw_str, size, 'RGBA')
The first argument to pygame.image.fromstring has to be a str.
So when frame_1 is your PIL image, convert it to a string with tostring, and load this string with pygame.image.fromstring.
You have to know the size of the image for this to work.
raw_str = frame_1.tostring("raw", 'RGBA')
pygame_surface = pygame.image.fromstring(raw_str, size, 'RGBA')

Adding noise to an image in increments

Hi I am trying to add noise to a QR image that I create, this is my code so far:
import numpy
import scipy
import scipy.misc
import sys
sys.path.append('M:/PythonMods')
import qrcode
if __name__ == "__main__":
myqr = qrcode.make("randomtexxxxxxxxxt")
#myqr.show()
myqr.save("M:/COMPUTINGSEMESTER2/myqr4.png")
filename = 'myqr4.png'
imagea = (scipy.misc.imread(filename)).astype(float)
poissonNoise = numpy.random.poisson(50,imagea.shape).astype(float)
noisyImage = imagea + poissonNoise
Please could someone advise me how I get it to show the noisy image? and how to save the image so I can test it?
Any help really appreciated.
edit
I tried adding this code to the program to get it to show the image:
from PIL import Image
myimage = Image.open(noisyImage)
myimage.load()
But then got this error:
Traceback (most recent call last):
File "M:\COMPUTINGSEMESTER2\untitled4.py", line 28, in <module>
myimage = Image.open(noisyImage)
File "Q:\PythonXY273_MaPS-T.v01\Python27\lib\site-packages\PIL\Image.py", line 1958, in open
prefix = fp.read(16)
AttributeError: 'numpy.ndarray' object has no attribute 'read'
Image.open needs an image file as parameter, use Image.fromarray:
im = Image.fromarray(noisyImage)
im.save("myFile.jpeg")
you may also use matplotlib module to show the image directly:
import matplotlib.pyplot as plt
plt.imshow(noisyImage) #Needs to be in row,col order
scipy.misc.imsave('NoisyImage.jpg', noisyImage)

Categories