简体   繁体   中英

How to save an input image into a variable and call it in another function?

I have written a code to compare two images and it is working fine. Now I want to develop an UI to browse the two get the two images as an input and then my code of comparison should work and give the results. Below is my code two browse the two different images from my local drive.

import PySimpleGUI as sg
import cv2
import numpy as np

supportedextensions = ['jpg','png']
layoutprefile = [
    [sg.Text('Select two images to proceed')],
    [sg.Text('Origi Image'), sg.Input(), sg.FileBrowse()],
    [sg.Text('Input Image'), sg.Input(), sg.FileBrowse()],
    # *list1,
    [sg.Output(size=(61, 5))],
    [sg.Submit('Compare'), sg.Cancel('Cancel')]
    ]
window = sg.Window('Image Compare', layoutprefile)
while True:    
    event, values = window.read()
    if event in (None, 'Exit', 'Cancel'):
        secondwindow = 0
        break
    elif event == 'Compare':

Now my below code is two compare two images

# Original image
      image = 
      gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
      histogram = cv2.calcHist([gray_image], [0], 
                                 None, [256], [0, 256])

           
        # Input1 image
      image1 = 
      gray_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
      histogram1 = cv2.calcHist([gray_image1], [0], 
                                  None, [256], [0, 256])

   
  
   
c1 = 0
   

i = 0
while i<len(histogram) and i<len(histogram1):
    c1+=(histogram[i]-histogram1[i])**2
    i+= 1
c1 = c1**(1 / 2)
   
  

if(c1==0):
    print("Input image is matching with original image.")
elif(c1>0 or c1<0):
   print("Input image is not matching with original image")

imS = cv2.resize(image, (250, 200))
imS1 = cv2.resize(image1, (250, 200))  

cv2.imshow("Original", imS)
cv2.imshow("Input1", imS1)

I need user input image to save in image and image 1 to compare. How to proceed to that?

you can get your sg.Input() values with the line event, values = window.read() and you can access your inputs in order to your input. your code will be like this:

  # Original image
  image = cv2.imread(values[0])
  gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  histogram = cv2.calcHist([gray_image], [0], 
                             None, [256], [0, 256])

       
    # Input1 image
  image1 = cv2.imread(values[1])
  gray_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
  histogram1 = cv2.calcHist([gray_image1], [0], 
                              None, [256], [0, 256])
  break

Note: you should close your window and destroy windows from opencv imshow with these lines at the end of your code:

cv2.waitKey()
cv2.destroyAllWindows()
window.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM