dropdown menu

Back To Home

Wednesday, November 27, 2019

python-zoom in zoom out image

Zoom in zoom out image for python.
Click on the image to zoom in.
Click on button to zoom out.

Python code:
# -*- coding: utf-8 -*-
# Advanced zoom for images of various types from small to huge up to several GB
import math
import warnings
import tkinter as tk
from tkinter import *
import os
from tkinter import ttk
from PIL import Image, ImageTk

class AutoScrollbar(ttk.Scrollbar):
    """ A scrollbar that hides itself if it's not needed. Works only for grid geometry manager """
    def set(self, lo, hi):
        if float(lo) <= 0.0 and float(hi) >= 1.0:
            self.grid_remove()
        else:
            self.grid()
            ttk.Scrollbar.set(self, lo, hi)

    def pack(self, **kw):
        raise tk.TclError('Cannot use pack with the widget ' + self.__class__.__name__)

    def place(self, **kw):
        raise tk.TclError('Cannot use place with the widget ' + self.__class__.__name__)

class CanvasImage:
    """ Display and zoom image """
 
 
    def __init__(self, placeholder, path):
        """ Initialize the ImageFrame """
        #a=open("x1.txt","r")
        #data=a.readlines()
        self.imscale=1.0
        #self.imscale = 1+(1*int(data[0])/100)  # scale for the canvas image zoom, public for outer classes
        self.__delta = 1.3 # zoom magnitude
        self.__filter = Image.ANTIALIAS  # could be: NEAREST, BILINEAR, BICUBIC and ANTIALIAS
        self.__previous_state = 0  # previous state of the keyboard
        self.path = path  # path to the image, should be public for outer classes
        # Create ImageFrame in placeholder widget
        self.__imframe = ttk.Frame(placeholder)  # placeholder of the ImageFrame object
        # Vertical and horizontal scrollbars for canvas
        hbar = AutoScrollbar(self.__imframe, orient='horizontal')
        vbar = AutoScrollbar(self.__imframe, orient='vertical')

        hbar.grid(row=1, column=0, sticky='we')
        vbar.grid(row=0, column=1, sticky='ns')
        # Create canvas and bind it with scrollbars. Public for outer classes
        self.canvas = tk.Canvas(self.__imframe, highlightthickness=0,
                                xscrollcommand=hbar.set, yscrollcommand=vbar.set)
        self.canvas.grid(row=0,column=0,sticky='nswe',columnspan=2)
        self.canvas.update()  # wait till canvas is created
           
        #e=tk.Button(self.__imframe,text="Zoom in",command=self.Zoom,height=3,width=10)
        #e.grid(row=2, column=0)
        f=tk.Button(self.__imframe,text="Zoom out",command=self.Zoom2,height=3,width=10)
        f.grid(row=2, column=0)
     
        f=tk.Label(self.__imframe,text="Tounch to zoom in",fg="blue",font=26)
        f.grid(row=3, column=0)
     
     
     
     
     
        hbar.configure(command=self.__scroll_x)  # bind scrollbars to the canvas
        vbar.configure(command=self.__scroll_y)
        # Bind events to the Canvas
     
     
        self.canvas.bind('<Configure>', lambda event: self.__show_image())  # canvas is resized
        self.canvas.bind('<ButtonPress-1>', self.__move_from)  # remember canvas position
        self.canvas.bind('<B1-Motion>',     self.__move_to)  # move canvas to the new position
        self.canvas.bind('<MouseWheel>', self.__wheel)  # zoom for Windows and MacOS, but not Linux
        self.canvas.bind('<Button-5>',   self.__wheel)  # zoom for Linux, wheel scroll down
        self.canvas.bind('<Button-4>',   self.__wheel)  # zoom for Linux, wheel scroll up
     
        self.canvas.bind('<Button-1>',   self.Zoom)  # zoom for Linux, wheel scroll up
     
        # Handle keystrokes in idle mode, because program slows down on a weak computers,
        # when too many key stroke events in the same time
        self.canvas.bind('<Key>', lambda event: self.canvas.after_idle(self.__keystroke, event))
        # Decide if this image huge or not
        self.__huge = False  # huge or not
        self.__huge_size = 14000  # define size of the huge image
        self.__band_width = 1024  # width of the tile band
        Image.MAX_IMAGE_PIXELS = 1000000000  # suppress DecompressionBombError for the big image
        with warnings.catch_warnings():  # suppress DecompressionBombWarning
            warnings.simplefilter('ignore')
            self.__image = Image.open(self.path)  # open image, but down't load it
        self.imwidth, self.imheight = self.__image.size  # public for outer classes
        if self.imwidth * self.imheight > self.__huge_size * self.__huge_size and \
           self.__image.tile[0][0] == 'raw':  # only raw images could be tiled
            self.__huge = True  # image is huge
            self.__offset = self.__image.tile[0][2]  # initial tile offset
            self.__tile = [self.__image.tile[0][0],  # it have to be 'raw'
                           [0, 0, self.imwidth, 0],  # tile extent (a rectangle)
                           self.__offset,
                           self.__image.tile[0][3]]  # list of arguments to the decoder
        self.__min_side = min(self.imwidth, self.imheight)  # get the smaller image side
        # Create image pyramid
        self.__pyramid = [self.smaller()] if self.__huge else [Image.open(self.path)]
        # Set ratio coefficient for image pyramid
        self.__ratio = max(self.imwidth, self.imheight) / self.__huge_size if self.__huge else 1.0
        self.__curr_img = 0  # current image from the pyramid
        self.__scale = self.imscale * self.__ratio  # image pyramide scale
        self.__reduction = 2  # reduction degree of image pyramid
        w, h = self.__pyramid[-1].size
        while w > 512 and h > 512:  # top pyramid image is around 512 pixels in size
            w /= self.__reduction  # divide on reduction degree
            h /= self.__reduction  # divide on reduction degree
            self.__pyramid.append(self.__pyramid[-1].resize((int(w), int(h)), self.__filter))
        # Put image into container rectangle and use it to set proper coordinates to the image
        self.container = self.canvas.create_rectangle((0, 0, self.imwidth, self.imheight), width=0)
        self.__show_image()  # show image on the canvas
        self.canvas.focus_set()  # set focus on the canvas
     
 
    def smaller(self):
        """ Resize image proportionally and return smaller image """
        w1, h1 = float(self.imwidth), float(self.imheight)
        w2, h2 = float(self.__huge_size), float(self.__huge_size)
        aspect_ratio1 = w1 / h1
        aspect_ratio2 = w2 / h2  # it equals to 1.0
        if aspect_ratio1 == aspect_ratio2:
            image = Image.new('RGB', (int(w2), int(h2)))
            k = h2 / h1  # compression ratio
            w = int(w2)  # band length
        elif aspect_ratio1 > aspect_ratio2:
            image = Image.new('RGB', (int(w2), int(w2 / aspect_ratio1)))
            k = h2 / w1  # compression ratio
            w = int(w2)  # band length
        else:  # aspect_ratio1 < aspect_ration2
            image = Image.new('RGB', (int(h2 * aspect_ratio1), int(h2)))
            k = h2 / h1  # compression ratio
            w = int(h2 * aspect_ratio1)  # band length
        i, j, n = 0, 1, round(0.5 + self.imheight / self.__band_width)
        while i < self.imheight:
            print('\rOpening image: {j} from {n}'.format(j=j, n=n), end='')
            band = min(self.__band_width, self.imheight - i)  # width of the tile band
            self.__tile[1][3] = band  # set band width
            self.__tile[2] = self.__offset + self.imwidth * i * 3  # tile offset (3 bytes per pixel)
            self.__image.close()
            self.__image = Image.open(self.path)  # reopen / reset image
            self.__image.size = (self.imwidth, band)  # set size of the tile band
            self.__image.tile = [self.__tile]  # set tile
            cropped = self.__image.crop((0, 0, self.imwidth, band))  # crop tile band
            image.paste(cropped.resize((w, int(band * k)+1), self.__filter), (0, int(i * k)))
            i += band
            j += 1
        print('\r' + 30*' ' + '\r', end='')  # hide printed string
        return image

    def redraw_figures(self):
        """ Dummy function to redraw figures in the children classes """
        pass

    def grid(self, **kw):
        """ Put CanvasImage widget on the parent widget """
        self.__imframe.grid(**kw)  # place CanvasImage widget on the grid
        self.__imframe.grid(sticky='nswe')  # make frame container sticky
        self.__imframe.rowconfigure(0, weight=1)  # make canvas expandable
        self.__imframe.columnconfigure(0, weight=1)
     
    def pack(self, **kw):
        """ Exception: cannot use pack with this widget """
        raise Exception('Cannot use pack with the widget ' + self.__class__.__name__)

    def place(self, **kw):
        """ Exception: cannot use place with this widget """
        raise Exception('Cannot use place with the widget ' + self.__class__.__name__)

    # noinspection PyUnusedLocal
    def __scroll_x(self, *args, **kwargs):
        """ Scroll canvas horizontally and redraw the image """
        self.canvas.xview(*args)  # scroll horizontally
        self.__show_image()  # redraw the image

    # noinspection PyUnusedLocal
    def __scroll_y(self, *args, **kwargs):
        """ Scroll canvas vertically and redraw the image """
        self.canvas.yview(*args)  # scroll vertically
        self.__show_image()  # redraw the image

    def __show_image(self):
        """ Show image on the Canvas. Implements correct image zoom almost like in Google Maps """
        box_image = self.canvas.coords(self.container)  # get image area
        box_canvas = (self.canvas.canvasx(0),  # get visible area of the canvas
                      self.canvas.canvasy(0),
                      self.canvas.canvasx(self.canvas.winfo_width()),
                      self.canvas.canvasy(self.canvas.winfo_height()))
        box_img_int = tuple(map(int, box_image))  # convert to integer or it will not work properly
        # Get scroll region box
        box_scroll = [min(box_img_int[0], box_canvas[0]), min(box_img_int[1], box_canvas[1]),
                      max(box_img_int[2], box_canvas[2]), max(box_img_int[3], box_canvas[3])]
        # Horizontal part of the image is in the visible area
        if  box_scroll[0] == box_canvas[0] and box_scroll[2] == box_canvas[2]:
            box_scroll[0]  = box_img_int[0]
            box_scroll[2]  = box_img_int[2]
        # Vertical part of the image is in the visible area
        if  box_scroll[1] == box_canvas[1] and box_scroll[3] == box_canvas[3]:
            box_scroll[1]  = box_img_int[1]
            box_scroll[3]  = box_img_int[3]
        # Convert scroll region to tuple and to integer
        self.canvas.configure(scrollregion=tuple(map(int, box_scroll)))  # set scroll region
        x1 = max(box_canvas[0] - box_image[0], 0)  # get coordinates (x1,y1,x2,y2) of the image tile
        y1 = max(box_canvas[1] - box_image[1], 0)
        x2 = min(box_canvas[2], box_image[2]) - box_image[0]
        y2 = min(box_canvas[3], box_image[3]) - box_image[1]
        if int(x2 - x1) > 0 and int(y2 - y1) > 0:  # show image if it in the visible area
            if self.__huge and self.__curr_img < 0:  # show huge image
                h = int((y2 - y1) / self.imscale)  # height of the tile band
                self.__tile[1][3] = h  # set the tile band height
                self.__tile[2] = self.__offset + self.imwidth * int(y1 / self.imscale) * 3
                self.__image.close()
                self.__image = Image.open(self.path)  # reopen / reset image
                self.__image.size = (self.imwidth, h)  # set size of the tile band
                self.__image.tile = [self.__tile]
                image = self.__image.crop((int(x1 / self.imscale), 0, int(x2 / self.imscale), h))
            else:  # show normal image
                image = self.__pyramid[max(0, self.__curr_img)].crop(  # crop current img from pyramid
                                    (int(x1 / self.__scale), int(y1 / self.__scale),
                                     int(x2 / self.__scale), int(y2 / self.__scale)))
            #
            imagetk = ImageTk.PhotoImage(image.resize((int(x2 - x1), int(y2 - y1)), self.__filter))
            imageid = self.canvas.create_image(max(box_canvas[0], box_img_int[0]),
                                               max(box_canvas[1], box_img_int[1]),
                                               anchor='nw', image=imagetk)
            self.canvas.lower(imageid)  # set image into background
            self.canvas.imagetk = imagetk  # keep an extra reference to prevent garbage-collection
         


    def __move_from(self, event):
        """ Remember previous coordinates for scrolling with the mouse """
        self.canvas.scan_mark(event.x, event.y)

    def __move_to(self, event):
        """ Drag (move) canvas to the new position """
        self.canvas.scan_dragto(event.x, event.y, gain=1)
        self.__show_image()  # zoom tile and show it on the canvas

    def outside(self, x, y):
        """ Checks if the point (x,y) is outside the image area """
        bbox = self.canvas.coords(self.container)  # get image area
        if bbox[0] < x < bbox[2] and bbox[1] < y < bbox[3]:
            return False  # point (x,y) is inside the image area
        else:
            return True  # point (x,y) is outside the image area

    def __wheel(self, event):
        """ Zoom with mouse wheel """
        x = self.canvas.canvasx(event.x)  # get coordinates of the event on the canvas
        y = self.canvas.canvasy(event.y)
        if self.outside(x, y): return  # zoom only inside image area
        scale = 1.0
        # Respond to Linux (event.num) or Windows (event.delta) wheel event
        if event.num == 5 or event.delta == -120:  # scroll down, smaller
            if round(self.__min_side * self.imscale) < 30: return  # image is less than 30 pixels
            self.imscale /= self.__delta
            scale        /= self.__delta
        if event.num == 4 or event.delta == 120:  # scroll up, bigger
            i = min(self.canvas.winfo_width(), self.canvas.winfo_height()) >> 1
            if i < self.imscale: return  # 1 pixel is bigger than the visible area
            self.imscale *= self.__delta
            scale        *= self.__delta
        # Take appropriate image from the pyramid
        k = self.imscale * self.__ratio  # temporary coefficient
        self.__curr_img = min((-1) * int(math.log(k, self.__reduction)), len(self.__pyramid) - 1)
        self.__scale = k * math.pow(self.__reduction, max(0, self.__curr_img))
        #
        self.canvas.scale('all', x, y, scale, scale)  # rescale all objects
        # Redraw some figures before showing image on the screen
        self.redraw_figures()  # method for child classes
        self.__show_image()
     
    def Zoom(self,event):
        #print("hll")
     
     
     
        """ Zoom with mouse wheel """     
        x = self.canvas.canvasx(event.x)  # get coordinates of the event on the canvas
        y = self.canvas.canvasy(event.y)
        #x = 10
        #y = 10
        if self.outside(x, y): return  # zoom only inside image area
        scale = 1.0
        # Respond to Linux (event.num) or Windows (event.delta) wheel event
        #if event.num == 5 or event.delta == -120:  # scroll down, smaller
        #    if round(self.__min_side * self.imscale) < 30: return  # image is less than 30 pixels
       #     self.imscale /= self.__delta
       #     scale        /= self.__delta
       # if event.num == 4 or event.delta == 120:  # scroll up, bigger
        i = min(self.canvas.winfo_width(), self.canvas.winfo_height()) >> 6
        if i < self.imscale: return  # 1 pixel is bigger than the visible area
     
   
        self.imscale *= self.__delta
        scale        *= self.__delta
        print(self.imscale )
        f=open("x1.txt","w+")
        f.writelines(str(self.imscale))
        f.close()
     
        #if(self.imscale >=12):
          #self.canvas.unbind('<Button-1>')
         
        #elif(self.imscale <12):
          #self.canvas.bind('<Button-1>',self.Zoom)
     
       
     
        # Take appropriate image from the pyramid
        k = self.imscale * self.__ratio  # temporary coefficient
 
        self.__curr_img = min((-1) * int(math.log(k, self.__reduction)), len(self.__pyramid) - 1)
        self.__scale = k * math.pow(self.__reduction, max(0, self.__curr_img))
     
        #

        self.canvas.scale('all', x, y, scale, scale)  # rescale all objects
        # Redraw some figures before showing image on the screen
        self.redraw_figures()  # method for child classes
     
        self.__show_image()
     
     
    def Zoom2(self):

        """ Zoom with mouse wheel """
        #x = self.canvas.canvasx(event.x)  # get coordinates of the event on the canvas
        #y = self.canvas.canvasy(event.y)
        x = 528
        y = 292
        if self.outside(x, y): return  # zoom only inside image area
        scale = 1.0
        # Respond to Linux (event.num) or Windows (event.delta) wheel event
        #if event.num == 5 or event.delta == -120:  # scroll down, smaller
        if round(self.__min_side * self.imscale) < 700: return  # image is less than 30 pixels
        print(round(self.__min_side * self.imscale))
       #     self.imscale /= self.__delta
       #     scale        /= self.__delta
       # if event.num == 4 or event.delta == 120:  # scroll up, bigger
        #i = min(self.canvas.winfo_width(), self.canvas.winfo_height()) >> 1
        #if i < self.imscale: return  # 1 pixel is bigger than the visible area
        self.imscale /= self.__delta
        scale        /= self.__delta
        # Take appropriate image from the pyramid
        k = self.imscale * self.__ratio  # temporary coefficient
        self.__curr_img = min((-1) * int(math.log(k, self.__reduction)), len(self.__pyramid) - 1)
        self.__scale = k * math.pow(self.__reduction, max(0, self.__curr_img))
        #
        self.canvas.scale('all', x, y, scale, scale)  # rescale all objects
        # Redraw some figures before showing image on the screen
        self.redraw_figures()  # method for child classes
        self.__show_image()






     
    def __keystroke(self, event):
        """ Scrolling with the keyboard.
            Independent from the language of the keyboard, CapsLock, <Ctrl>+<key>, etc. """
        if event.state - self.__previous_state == 4:  # means that the Control key is pressed
            pass  # do nothing if Control key is pressed
        else:
            self.__previous_state = event.state  # remember the last keystroke state
            # Up, Down, Left, Right keystrokes
            if event.keycode in [68, 39, 102]:  # scroll right, keys 'd' or 'Right'
                self.__scroll_x('scroll',  1, 'unit', event=event)
            elif event.keycode in [65, 37, 100]:  # scroll left, keys 'a' or 'Left'
                self.__scroll_x('scroll', -1, 'unit', event=event)
            elif event.keycode in [87, 38, 104]:  # scroll up, keys 'w' or 'Up'
                self.__scroll_y('scroll', -1, 'unit', event=event)
            elif event.keycode in [83, 40, 98]:  # scroll down, keys 's' or 'Down'
                self.__scroll_y('scroll',  1, 'unit', event=event)

    def crop(self, bbox):
        """ Crop rectangle from the image and return it """
        if self.__huge:  # image is huge and not totally in RAM
            band = bbox[3] - bbox[1]  # width of the tile band
            self.__tile[1][3] = band  # set the tile height
            self.__tile[2] = self.__offset + self.imwidth * bbox[1] * 3  # set offset of the band
            self.__image.close()
            self.__image = Image.open(self.path)  # reopen / reset image
            self.__image.size = (self.imwidth, band)  # set size of the tile band
            self.__image.tile = [self.__tile]
            return self.__image.crop((bbox[0], 0, bbox[2], band))
        else:  # image is totally in RAM
            return self.__pyramid[0].crop(bbox)

    def destroy(self):
        """ ImageFrame destructor """
        self.__image.close()
        map(lambda i: i.close, self.__pyramid)  # close all pyramid images
        del self.__pyramid[:]  # delete pyramid list
        del self.__pyramid  # delete pyramid variable
        self.canvas.destroy()
        self.__imframe.destroy()
     
 
     
 

class MainWindow(ttk.Frame):
    """ Main window class """
    def __init__(self, mainframe, path):
        """ Initialize the main Frame """
        ttk.Frame.__init__(self, master=mainframe)
        self.master.title('Advanced Zoom v3.0')
        #self.master.geometry('800x450+100+10')  # size of the main window
        self.master.geometry('980x670+10+10')  # size of the main window
        self.master.rowconfigure(0, weight=10)  # make the CanvasImage widget expandable
        self.master.columnconfigure(0, weight=10)
        canvas = CanvasImage(self.master, path)  # create widget
        canvas.grid(row=0, column=0)  # show widget
     
        #def capture():
           #print("hrllo")
           #f=open("x1.txt","w+")
           #f.writelines(str(w.get()))
           #os.system('python3 /home/pi/Desktop/displayimage1.py')
         
         
        #e=tk.Button(self.master,text="Capture",command=capture,height=3,width=10)
        #e.grid(row=1, column=0)
     
        #w = tk.Scale(self.master, from_=0, to=100,orient=HORIZONTAL)
        #w.grid(row=1, column=1)
        #print(w.get())
     
   

filename = 'C:/Users/HP/Desktop/sunflower.jpg'  # place path to your image here
#filename = 'd:/Data/yandex_z18_1-1.tif'  # huge TIFF file 1.4 GB
#filename = 'd:/Data/The_Garden_of_Earthly_Delights_by_Bosch_High_Resolution.jpg'
#filename = 'd:/Data/The_Garden_of_Earthly_Delights_by_Bosch_High_Resolution.tif'
#filename = 'd:/Data/heic1502a.tif'
#filename = 'd:/Data/land_shallow_topo_east.tif'
#filename = 'd:/Data/X1D5_B0002594.3FR'


#image="/home/pi/Andromeda_application/tmp2/amount.png"
#image_circle="/home/pi/Andromeda_application/tmp2/amount_circle.png"
#path=""

 # make sure file exists, else show an error
#if (os.path.isfile(image) and not os.path.isfile(image_circle)):
#   app = MainWindow(tk.Tk(), path="/home/pi/Andromeda_application/tmp2/amount.png")
 
#else:
app = MainWindow(tk.Tk(), path=filename)


app.mainloop()



                                                 

python tkinter-Progress bar

loading indicator to show the processing progress.
2 types:
1)determinate
2)indeterminate

python code:
from tkinter import ttk

from tkinter import *
root=Tk()
pb2 = ttk.Progressbar(root, mode='determinate', name='pb2')
pb2.grid(row=1, column=0, columnspan=2, pady=5, padx=10)

pb2.start()


root.mainloop()

                                                   

python-count repeated word in a file

count repeated word in a file using python scan line by line.

Python code:
f = open("/home/pi/Desktop/file",'r')

words_dict={}
for i in f.read().split():
    word=i.lower()
    words_dict[word]= words_dict.get(word,0) + 1
for key in words_dict.keys():
    print (str(key)+' = '+str(words_dict[key]))

file:
a23
233
6
544
4
2
4
7
9
0


                                         

python tkinter- close,minimize,maximize off

This is the way to off python tkinter close,minimize,maximize.
This is to prevent user click to close,minimise,maximize as we wants fix screen.
It's like wallpaper, cannot click and it is fixed.

Python code:

from tkinter import *
root=Tk()
root.geometry('500x500+100+100')
photo=PhotoImage(file="/home/pi/Desktop/download.png")
label=Label(root ,image=photo)
label.pack()
root.overrideredirect(1)
root.mainloop()

                                                     

Thursday, November 21, 2019

Lauch python script at startup automatically

Here is example how to launch python script automatically at start up.

Video1:

Video2:                                     
                                                   

python- run mutiple program in one run(parallel processing)

Here we have 2 functions func1 and func2 and we can run it parallel using multiprocessing module for python.

Python code:

from multiprocessing import Process

def func1():
  print ('func1: starting')
  for i in range(10000000): pass
  print ('func1: finishing')

def func2():
  print ('func2: starting')
  for i in range(10000000): pass
  print ('func2: finishing')

def runInParallel(*fns):
  proc = []
  for fn in fns:
    p = Process(target=fn)
    p.start()
    proc.append(p)
  for p in proc:
    p.join()

runInParallel(func1, func2)


                                          

Friday, November 15, 2019

python- control android camera

Control camera using module for python and transfer picture direct to pc.
Applicable to window or linux environment.
In order to call command prompt we need to import os.
module shutil mainly used to copy file.
tkinter is used to write gui.
adb shell are the adroid command.

following command to install ADB in linux: 
sudo apt-get install adb

Don't forget to enable phone in usb debugging mode.
https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm

Python code:
from tkinter import *
import os
import shutil

root=Tk()

def preview():
    os.system('adb shell "am start -a android.media.action.STILL_IMAGE_CAMERA"')
 
def capture():
    os.system('adb shell input keyevent 27')
 
def focus():
    os.system('adb shell "input keyevent KEYCODE_FOCUS"')
 
def copy():
    os.system('adb pull /sdcard/DCIM/Camera/ /home/pi/Desktop/')
 
    os.system('adb shell rm -rf /sdcard/DCIM/Camera/*')
    os.system('adb shell mount -o remount,rw /sdcard')
    for file in os.listdir("/home/pi/Desktop/Camera"):
        newfile = "/home/pi/Desktop/Camera/image.png"
        shutil.move(os.path.join("/home/pi/Desktop/Camera",file),newfile)
 
 
a=Button(root,text="preview",command=preview,height=3,width=10)
a.grid()
b=Button(root,text="capture",command=capture,height=3,width=10)
b.grid()
d=Button(root,text="focus",command=focus,height=3,width=10)
d.grid()
e=Button(root,text="copy",command=copy,height=3,width=10)
e.grid()

root.mainloop()

Part1:
                                          

Part2:                              

                                  

                                                 

Solved python tkinter error- couldn't recognize data in image file

This issue happened while tkinter would like to show image in label using PIL module.
cv2 module command was used to solved the issue.
tkinter module was used to write the gui.

import cv2
img=cv2.imread("md_5aba147bcacf2.png")
cv2.imwrite("md_5aba147bcacf2.png",img)

Python code:

from tkinter import *
from PIL import Image, ImageTk
import cv2

root = Tk()

labelFrame =Frame(root,width=10,height=10)
labelFrame.grid(row=0, column=0)

img=cv2.imread("md_5aba147bcacf2.png")
cv2.imwrite("md_5aba147bcacf2.png",img)
photo=PhotoImage(file="md_5aba147bcacf2.png")
label=Label(labelFrame,image=photo)
label.grid(row=1, column=1)


# Determine the origin by clicking
def getorigin(eventorigin):
    global x0,y0
    x0 = eventorigin.x
    y0 = eventorigin.y
    print(x0,y0)
 
#mouseclick event
label.bind("<Button 1>",getorigin)

root.mainloop()               

                                                         


                                                     

python-crop certain dimension from image

This method is useful to crop an image. Small size from big image.

Python code:

import cv2

img = cv2.imread("download.jpeg")
crop_img = img[0:500,0:500]

cv2.imwrite('download2.jpeg',crop_img)
         
                                                     

Thursday, November 14, 2019

python- get x,y location of an image

Get x,y location of an image is very useful. We can do colour detection on certain fixed point of a product in industry or many others applications. This tutorial is just to show how to get the x,y coordinate of an image.

 Python code:

from tkinter import *
from PIL import Image, ImageTk
import cv2

root = Tk()

labelFrame =Frame(root,width=10,height=10)
labelFrame.grid(row=0, column=0)

img=cv2.imread("md_5aba147bcacf2.png")
cv2.imwrite("md_5aba147bcacf2.png",img)
photo=PhotoImage(file="md_5aba147bcacf2.png")
label=Label(labelFrame,image=photo)
label.grid(row=1, column=1)


# Determine the origin by clicking
def getorigin(eventorigin):
    global x0,y0
    x0 = eventorigin.x
    y0 = eventorigin.y
    print(x0,y0)
 
#mouseclick event
label.bind("<Button 1>",getorigin)

root.mainloop()

                                                                 


Python- match character and delete it

Matched 7 in reference file and delete from main file.

Python code:
                              
infile = "yourfile.txt"
outfile = "yourfile2.txt"

with open("file2.txt", "r") as f:
    delete_list = f.readlines()

fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
    
    for word in delete_list:
        
        line = line.replace(word, "")
        print(line)
    fout.writelines(line)

fin.close()
fout.close()

file2:
7

yourfile:
1
2
3
4
5
6
7
8

yourfile2:
1
2
3
4
5
6

8



                                       

python- match word in a file not single character

Match whole word albert or robert not al or b and etc.

Python code:

import re

with open('line.txt', 'r') as fh:
    contents = fh.read()

loop = True
while loop:
    user_input = input('Enter a name: ').strip()
    if (re.search(r'\b'+ re.escape(user_input) + r'\b', contents, re.MULTILINE)):
        print("That name exists!")
    else:

        print("Couldn't find the name.")


line.txt
albert
robert
                                              
                                                               

Wednesday, November 13, 2019

python enumerate concept

Enumerate has 2 variables that very useful - count and element.
count - count number of line starting from 0. count+1 so that starting from 1.
element - is the full content of the line e.g.saya or dia and etc.

Code:

with open("line.txt") as f:
   for count, element in enumerate(f):
        pass
   print (count+1)
   print(element)

line.txt:
saya
dia
a
130 30 80
255 240 255
                                 

Monday, November 11, 2019

python gui - change image immediately click on button

change image immediately by click on button.

Codes:

import tkinter as tk
from PIL import ImageTk, Image

def next(panel):
    path = "download.jpeg"
    img = ImageTk.PhotoImage(Image.open(path))
    panel.configure(image=img)
    panel.image = img # keep a reference!

def prev(panel):
    path = "download (1).jpeg"
    img = ImageTk.PhotoImage(Image.open(path))
    panel.configure(image=img)
    panel.image = img # keep a reference!

#Create main window
window = tk.Tk()

#divide window into two sections. One for image. One for buttons
top = tk.Frame(window)
top.pack(side="top")
bottom = tk.Frame(window)
bottom.pack(side="bottom")

#place image
path = "download (1).jpeg"
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img)
panel.image = img # keep a reference!
panel.pack(side = "top", fill = "both", expand = "yes")

#place buttons
prev_button = tk.Button(window, text="Previous", width=10, height=2, command=lambda: prev(panel))
prev_button.pack(in_=bottom, side="left")
next_button = tk.Button(window, text="Next", width=10, height=2, command=lambda: next(panel))
next_button.pack(in_=bottom, side="right")

#Start the GUI
window.mainloop()

                                                 

python gui - Change image immediately with mouse click on image

Change image immediately with mouse click on image.

Codes:

from tkinter import *
from PIL import ImageTk, Image

root=Tk()

#place image
path = "download (1).jpeg"
img = ImageTk.PhotoImage(Image.open(path))
panel = Label(root, image = img)
panel.image = img # keep a reference!
panel.pack(side = "top", fill = "both", expand = "yes")


def getorigin(img):
    path = "download (2).jpeg"
    img = ImageTk.PhotoImage(Image.open(path))
    panel.configure(image=img)
    panel.image = img # keep a reference!


#mouseclick event
panel.bind("<Button 1>",getorigin)


#Start the GUI
root.mainloop()



Tuesday, November 5, 2019

Count number of repeated words in a file

Count number of repeated words in a file using python.
                                 
                                       
                                                         

Monday, November 4, 2019

Solved: Can't find python at command prompt

Here is the tips to install python and run python at command prompt.
                                                       
                                                   

set dimension and position of frame of python gui

Sometime we need to set the location for pop out screen and also the size of frame.
                                     

Sunday, November 3, 2019

Easy way for object detection-take 5 minutes to set up

Only need 10 lines of codes to perform object detection.

Link:
https://towardsdatascience.com/object-detection-with-10-lines-of-code-d6cb4d86f606?gi=1476f5306590

c++:
https://www.microsoft.com/en-us/download/details.aspx?id=53587

If you have issue for tensorflow (just pip install tensorflow==1.13):
https://github.com/OlafenwaMoses/ImageAI/issues/367 
                         
                                
                                                         

Solved:install pip in python3.3 or 2.6,.3.2

This is to show how to install pip in both pthon3 or python2.

Part1:


Part2:
                                       

Create exe from mutiple python files and images-cxfreeze

we will use the module of cxfreeze to create the exe for mutiples python and of course it can also include icon image or image that attached to python.

To install cx_freeze:

Go to command prompt--> 



To lauch the file use this command (Go to location of your setup.txt file):

python setup.txt build