tkinter: I need help to implement the image difference function in my OpenCV image processing GUI Python script

I want to improve and make some modifications to my Python code for image processing of the OpenCV GUI. The following is my code:

import tkinter as tk
from tkinter import filedialog, messagebox
import os
import cv2
from PIL import Image, ImageTk
from skimage.metrics import structural_similarity

class Button:

    def __init__(self, root, frame2):
        self.root = root
        self.frame2 = frame2
        self.radio_var = tk.IntVar()
        self.path_selected = 'none'
        self.paths = ()
        self.radio_handle = ()
        self.check_value = ()

    def on_click_select_button(self, fname_label):
        #global fname_label
        print('select button clicked')
        fileType = (('jpg/png file', ('*.jpg', '*.png')))
        self.path_selected = filedialog.askopenfilename(filetypes=fileType)
        fname_label('text') = os.path.basename(self.path_selected)

    def on_click_upload_button(self, path='None', image='None'):
        print('upload button clicked')

        if path == 'None':
            path = self.path_selected
        else:
            cv2.imwrite(path, image)

        if path in self.paths:
            messagebox.showerror('Upload Error', '"'
                                 + path
                                 + '"' + ' is already uploaded.')
        else:
            self.paths.append(path)
            self.create_radio_button(path)

    def on_click_show_button(self):
        print('showButton clicked')
        image = cv2.imread(self.paths(self.radio_var.get()))


        file_name = os.path.basename(self.paths(self.radio_var.get()))
        name, ext = os.path.splitext(file_name)
        path = 'images/' + name + '_' + ext

        # cv2.imwrite(path, image)
        self.open_image_window(path, image)

    def create_radio_button(self, path):

        image = cv2.imread(path)
        # image = cv2.resize(image,(120,120))
        image = self.scale_to_height(image, 120)
        image_tk = self.to_tk_image(image)

        radio_button = tk.Radiobutton(self.frame2, image=image_tk,
                                      value=len(self.radio_handle),
                                      variable=self.radio_var)
        self.radio_var.set(0)
        self.radio_handle.append(radio_button)
        self.check_value.append(self.radio_var)

        radio_button.grid(row=(len(self.radio_handle) - 1) // 3,
                          column=(len(self.radio_handle) - 1) % 3)
        self.root.mainloop()

    def open_image_window(self, path, image):

        if image.shape(0) > 300:
            image = self.scale_to_height(image, 300)

        img_win = tk.Toplevel(self.root)
        fname = os.path.basename(path)
        img_win.title(fname)
        img_canvas = tk.Canvas(img_win, width=image.shape(1),
                               height=image.shape(0))
        img_canvas.pack()
        image_tk = self.to_tk_image(image)
        img_canvas.create_image(0, 0, image=image_tk, anchor='nw')

        uploadButton2 = tk.Button(img_win, text='upload',
                                  command=lambda: self.on_click_upload_button(path, image))
        uploadButton2.pack()

        self.root.mainloop()

    def to_tk_image(self, image_bgr):
        image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
        image_pil = Image.fromarray(image_rgb)
        image_tk = ImageTk.PhotoImage(image_pil)

        return image_tk

    def scale_to_height(self, img, height):
        scale = height / img.shape(0)
        return cv2.resize(img, dsize=None, fx=scale, fy=scale)

class Sample_Button:

    def __init__(self, root, frame4):
        self.Sample_root = root
        self.frame4 = frame4
        self.Sample_radio_var = tk.IntVar()
        self.Sample_path_selected = 'none'
        self.Sample_paths = ()
        self.Sample_radio_handle = ()
        self.Sample_check_value = ()

    def on_click_select_button_Sample(self, Sample_fname_label):
        print('select Sample button clicked')
        Sample_fileType = (('jpg/png file', ('*.jpg', '*.png')))
        self.Sample_path_selected = filedialog.askopenfilename(filetypes=Sample_fileType)
        Sample_fname_label('text') = os.path.basename(self.Sample_path_selected)

    def on_click_upload_button_Sample(self, Sample_path='None', Sample_image='None'):
        print('upload Sample button clicked')

        if Sample_path == 'None':
            Sample_path = self.Sample_path_selected
        else:
            cv2.imwrite(Sample_path, Sample_image)

        if Sample_path in self.Sample_paths:
            messagebox.showerror('Upload Error', '"'
                                 + Sample_path
                                 + '"' + ' Sample is already uploaded.')
        else:
            self.Sample_paths.append(Sample_path)
            self.create_Sample_radio_button(Sample_path)

    def on_click_show_button_Sample(self):
        print('show Sample Button clicked')
        Sample_image = cv2.imread(self.Sample_paths(self.Sample_radio_var.get()))

        Sample_file_name = os.path.basename(self.Sample_paths(self.Sample_radio_var.get()))
        Sample_name, ext = os.path.splitext(Sample_file_name)
        Sample_path = 'Sample_images/' + Sample_name + '_' + ext

        # cv2.imwrite(path, image)
        self.open_Sample_image_window(Sample_path, Sample_image)

    def create_Sample_radio_button(self, Sample_path):

        Sample_image = cv2.imread(Sample_path)

        # image = cv2.resize(image,(120,120))
        Sample_image = self.scale_to_height_Sample(Sample_image, 120)
        Sample_image_tk = self.Sample_to_tk_image(Sample_image)

        Sample_radio_button = tk.Radiobutton(self.frame4, image=Sample_image_tk,
                                      value=len(self.Sample_radio_handle),
                                      variable=self.Sample_radio_var)
        self.Sample_radio_var.set(0)
        self.Sample_radio_handle.append(Sample_radio_button)
        self.Sample_check_value.append(self.Sample_radio_var)

        Sample_radio_button.grid(row=(len(self.Sample_radio_handle) - 1) // 3,
                          column=(len(self.Sample_radio_handle) - 1) % 3)
        self.Sample_root.mainloop()

    def open_Sample_image_window(self, Sample_path, Sample_image):

        if Sample_image.shape(0) > 300:
            Sample_image = self.scale_to_height_Sample(Sample_image, 300)

        Sample_img_win = tk.Toplevel(self.Sample_root)
        Sample_fname = os.path.basename(Sample_path)
        Sample_img_win.title(Sample_fname)
        Sample_img_canvas = tk.Canvas(Sample_img_win, width=Sample_image.shape(1),
                               height=Sample_image.shape(0))
        Sample_img_canvas.pack()
        Sample_image_tk = self.Sample_to_tk_image(Sample_image)
        Sample_img_canvas.create_image(0, 0, image=Sample_image_tk, anchor='nw')

        uploadSampleButton2 = tk.Button(Sample_img_win, text='Upload Sample',
                                  command=lambda: self.on_click_upload_button_Sample(Sample_path, Sample_image))
        uploadSampleButton2.pack()

        self.Sample_root.mainloop()

    def Sample_to_tk_image(self, Sample_image_bgr):
        Sample_image_rgb = cv2.cvtColor(Sample_image_bgr, cv2.COLOR_BGR2RGB)
        Sample_image_pil = Image.fromarray(Sample_image_rgb)
        Sample_image_tk = ImageTk.PhotoImage(Sample_image_pil)

        return Sample_image_tk

    def scale_to_height_Sample(self, Sample_img, height):
        scale = height / Sample_img.shape(0)
        return cv2.resize(Sample_img, dsize=None, fx=scale, fy=scale)


class Merged_Button():

    #def __init__(self, root, frame6, frame5):



    def image_diff(self, file_name, Sample_file_name):
        self.Sample_radio_var = tk.IntVar()
        self.radio_var = tk.IntVar()
        self.paths = ()
        self.Sample_paths = ()

        Sample_file_name = os.path.basename(self.Sample_paths(self.Sample_radio_var.get()))
        Sample_image = cv2.imread(Sample_file_name)
        print(Sample_image)
        Sample_name, ext = os.path.splitext(Sample_file_name)
        Sample_path = 'Sample_images/' + Sample_name + '_' + ext
        print(Sample_path)
        #Sample_image = cv2.imread(Sample_file_name)
        #print(Sample_image)
        file_name = os.path.basename(self.paths(self.radio_var.get()))
        image = cv2.imread(file_name)
        print(image)
        name, ext = os.path.splitext(file_name)
        path = 'images/' + name + '_' + ext
        print(path)
        #image = cv2.imread(file_name)
        #print(image)

        Greyscale_Sample_image = cv2.cvtColor(Sample_image, cv2.COLOR_RGB2GRAY)
        Greyscale_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

        (score, diff) = structural_similarity(Greyscale_image, Greyscale_Sample_image, full=True)  # bw_
        print("Image similarity %ge =", score * 100)

        diff = (diff * 255).astype("uint8")

        cv2.imshow('diff', diff)
        cv2.waitKey()


if __name__ == '__main__':
    os.makedirs('images', exist_ok=True)
    root = tk.Tk()
    root.title('Image GUI')
    root.geometry('1280x960')


#######################################Reference#########################################################
    pw_left = tk.Frame(root, relief='ridge', borderwidth=4)
    pw_left.pack(side='left', anchor='nw')
    pw_right = tk.Frame(root, relief='ridge', borderwidth=4)
    pw_right.pack(side='left', anchor='nw')
    frame1 = tk.Frame(pw_left, bd=2, relief="ridge")
    frame1.pack()
    frame2 = tk.LabelFrame(pw_right, bd=2, text='Uploaded images')
    frame2.pack(side='left', anchor='nw')

    button = Button(root, frame2)
    label = tk.Label(frame1, text='File:')
    label.grid(row=0, column=0)
    file_name_label = tk.Label(frame1, text='-----not selected-----', width=20, bg='white')
    file_name_label.grid(row=0, column=1)
    select_button = tk.Button(frame1, text='select', command=lambda: button.on_click_select_button(file_name_label))
    select_button.grid(row=0, column=2)
    uploadButton = tk.Button(frame1, text='Upload',
                             command=lambda: button.on_click_upload_button())
    uploadButton.grid(row=0, column=3)

######################################################Sample####################################################3333333#
    os.makedirs('Sample_images', exist_ok=True)
    pw_left = tk.Frame(root, relief='ridge', borderwidth=4)
    pw_left.pack(side='left', anchor='nw')
    pw_right = tk.Frame(root, relief='ridge', borderwidth=4)
    pw_right.pack(side='left', anchor='nw')
    frame3 = tk.Frame(pw_left, bd=2, relief="ridge")
    frame3.pack()
    frame4 = tk.LabelFrame(pw_right, bd=2, text='Uploaded Sample images')
    frame4.pack(side='right', anchor='nw')


    Sample_button = Sample_Button(root, frame4)
    Sample_label = tk.Label(frame3, text='Sample File:')
    Sample_label.grid(row=0, column=0)
    Sample_file_name_label = tk.Label(frame3, text='-----not selected-----', width=20, bg='white')
    Sample_file_name_label.grid(row=0, column=1)
    Sample_select_button = tk.Button(frame3, text='select',
                                     command=lambda: Sample_button.on_click_select_button_Sample(
                                         Sample_file_name_label))
    Sample_select_button.grid(row=0, column=2)
    Sample_uploadButton = tk.Button(frame3, text='Upload',
                                    command=lambda: Sample_button.on_click_upload_button_Sample())
    Sample_uploadButton.grid(row=0, column=3)

#############################################merged########################################################


    pw_left_merge = tk.Frame(root, relief='ridge', borderwidth=4)
    pw_left_merge.pack(side='left', anchor='w')
    pw_right_merge = tk.Frame(root, relief='ridge', borderwidth=4)
    pw_right_merge.pack(side='left', anchor='w')
    frame5 = tk.LabelFrame(pw_left_merge, bd=2, relief="ridge")
    frame5.pack()
    frame6 = tk.LabelFrame(pw_right_merge, bd=2, text='Uploaded Merged images')
    frame6.pack(side='left', anchor='w')
    merged_button = Merged_Button()
    Difference_label = tk.LabelFrame(frame5, text='Merge File:')
    Difference_label.grid(row=7, column=0)

         ##########################select both files brom sample and reference label########################

    Difference_select_button = tk.Button(frame5, text='Difference_select',
                                         command=lambda: merged_button.image_diff(file_name_label('text'),
                                                                                  Sample_file_name_label('text')))
    Difference_select_button.grid(row=0, column=2)


    root.mainloop()

The GUI window for my code is as follows
enter the description of the image here

Modifications: I need to modify this GUI so that it shows the image difference between the sample and the reference images. I have encoded the script, but I have problems to implement it in the GUI. When I press the exit of a button, I get the image difference on the label.

Why "in the camera" instead of in subsequent processing?

There is a very common attitude among photographers that the appearance of a photo (for example, exposure) must be created using the camera's functions (aperture, shutter, etc .; it does not include the "touch up" functions integrated in the software). newer cameras) than postprocessing (Photoshop and the like).

Obviously, before the digital era, this was largely a practical matter. Now we have more tools at our disposal.

What is the reasoning for doing things in the camera instead of the subsequent processing, given the current technology available?

c ++ – MySQL / MariaDB Data extraction / Chain manipulation / "TopN" processing => Performance approach

The somewhat simplified task is to efficiently extract around 250,000 user records from a mariadb and do some string mixing and then find the "TopN" (for example, the most common names, etc.) for 3 fields.

The focus is on performance (the real case is bigger). First of all, the focus is on the algorithm: I think that the unordered_map hash table followed by partial_sort_copy is quite efficient, but happy to prove it wrong. The second focus is on string mechanics. Do I extract / munging and map efficiently? With so few std::string copies as possible? (I realize that std :: tolower () is not correctly compatible with utf8). I decided on a std::move in a place. See comments.

The reference point is a similar code in ("cough") php which really is not half bad! Approximately half the speed of this c ++ code compiled with clang-8 -O3. The database is localhost and the data is in memory. If I repeat the code in a loop, I get 50% of one CPU core in this process and 50% of another CPU core in the mysqld process. I realize that the database is a big part of the problem here. Trying to minimize the rest.

It is not particularly "generic" and does not attempt to be, just delete the quick code.

Code review / tips please? Timing results at the bottom (my own mini timer class, not relevant). Connection details omitted.

By the way: I thought about how to "do it in the database". I can make one (not 3!) Fields in the DB in 300 ms (more than it takes c ++ for all 3 fields). The DB query cannot do all 3 fields at the same time. I used: "SELECT field, count (*) as cnt group by field order by cnt desc limit 10;". Even the php The code is faster than that.


#include "mariadb++/account.hpp"
#include "mariadb++/concurrency.hpp"
#include "mariadb++/connection.hpp"
#include "mariadb++/statement.hpp"
#include "mariadb++/types.hpp"
#include 
#include 
#include 
#include 

void ltrim(std::string& s) {
  s.erase(s.begin(), std::find_if(s.begin(), s.end(), ()(int ch) { return !std::isspace(ch); }));
}

void rtrim(std::string& s) {
  s.erase(std::find_if(s.rbegin(), s.rend(), ()(int ch) { return !std::isspace(ch); }).base(),
          s.end());
}

void trim(std::string& s) { ltrim(s); rtrim(s); }

void strtolower(std::string& s) {
  std::transform(s.begin(), s.end(), s.begin(),
                 ()(unsigned char c) { return std::tolower(c); }
  );
}

std::vector> top_n(const std::unordered_map& map, int n) {
  std::vector> top_n(n, {"", 0});
  std::partial_sort_copy(map.begin(), map.end(), top_n.begin(), top_n.end(),
                         ()(auto& a, auto& b) { return a.second > b.second; });
  return top_n;
}

void print (const std::vector>& top_n) {
  std::for_each(top_n.begin(), top_n.end(),
                ()(auto& e) { std::cout << e.first << ": " << e.second << "n"; });
}

int main() {
  std::shared_ptr m_con = con();
  mariadb::statement_ref qry = m_con->create_statement("select email,firstname,lastname from member");

  std::unordered_map domains, firstnames, lastnames;
  {
    Timer t1("fetch");
    mariadb::result_set_ref res = qry->query();
    while (res->next()) {
      // mariadb++ creates a copy, but it needs to. The result row will die shortly.
      std::string domain = res->get_string(0);
      trim(domain); // in place
      if (size_t pos = domain.find('@'); pos != std::string::npos) {
        strtolower(domain); // in place
        // this temporary will get moved
        domains(domain.substr(pos + 1))++;
      }

      std::string firstname = res->get_string(1);
      trim(firstname);
      strtolower(firstname);
      // godbolt testing seems to show std::move prevents a copy here
      firstnames(std::move(firstname))++;

      std::string lastname = res->get_string(2);
      trim(lastname);
      strtolower(lastname);
      lastnames(std::move(lastname))++;
    }
  }
  {
    const int n = 10;
    Timer t1("freqs");
    std::cout << "ndomainsn";
    print(top_n(domains, n));
    std::cout << "nfirstnamesn";
    print(top_n(firstnames, n));
    std::cout << "nlastnamesn";
    print(top_n(lastnames, n));
  }
}

Basic results of profile creation (and output, so it is more obvious what the code does).

fetch=262.02ms

domains
t...sanitised: 53687
g...: 41827
h...: 17583
h...: 12357
b...: 12141
y...: 8511
y...: 3967
a...: 3942
i...: 3682
o...: 3274

firstnames
david: 4042
john: 3348
james: 2774
paul: 2567
andrew: 2410
richard: 2317
peter: 2277
mark: 2159
sarah: 1929
michael: 1925

lastnames
smith: 2142
jones: 1652
williams: 1187
taylor: 1072
davies: 964
brown: 939
wilson: 784
evans: 776
thomas: 709
johnson: 597
freqs=3.15255ms

vulkan: texture processing is buffered in a single texture

I'm trying to render multiple font textures in a single texture,
My problem is that each font texture is repeated, but I would like to have only one instance of that font character.

Example of the problem below.

rendered fonts

My code that I use, to copy the buffers to the texture is this


        for (_key, value) in font_instance.characters.iter() {
            let image_buffer = system
                .device
                .create_buffer_mapped(value.data.len(), wgpu::BufferUsage::COPY_SRC)
                .fill_from_slice(&value.data);

            encoder.copy_buffer_to_texture(
                wgpu::BufferCopyView {
                    buffer: &image_buffer,
                    offset: 0,
                    row_pitch: 4 * value.width,
                    image_height: value.height,
                },
                wgpu::TextureCopyView {
                    texture: &texture,
                    mip_level: 0,
                    array_layer: 0,
                    origin: wgpu::Origin3d {
                        x: value.x as f32,
                        y: value.y as f32,
                        z: 0.0,
                    },
                },
                wgpu::Extent3d {
                    width: value.width,
                    height: value.height,
                    depth: 1,
                },
            );
        }

SSRS processing parameters in a URL

We have a private SSRS database and we have created a public atom URL to import the data into Google Sheet. It works, but returns each row as a string. It does not return in table format. There are no columns.

The URL has the following format:

= importfeed ("SERVER: / FOLDERLOCATION /% 252fJK% 252fFOLDER% 252fFILENAME & rc: ItemPath = Tablix1 / atom? token =! xyz"

And return as "A B C D" instead of "A" "B" "C" "D".

What do we need to add in the URL so that the data is returned in a table format?

United States: visa processing to attend the company's conference in the USA. UU. while working remotely from Bangladesh

I work for a US software company. UU. Remote from Bangladesh and my employer wants me to join a conference with an associated company that invests in our company.

My employer booked air tickets, the hotel reservation as part of the conference and I booked a hotel in Los Angeles outside of the conference days.

I sent form D160 myself and requested a B2 business visa that is the only purpose and my employer will send an invitation letter before the interview at the embassy that I will take with me for an interview.

Is there anything the employer should mention in the invitation letter and any other paperwork or invitation must send it directly to the embassy (again, nonimmigrant visa) or is there something I am missing?

I know that your many software engineers work remotely for the US software company. UU.
from other countries and expert help will be appreciated.

image processing – Conical quantization

In Gonzalez et al it is mentioned that the conical quantization is

enter the description of the image here

I can't solve this. I've searched the entire Internet, but nothing like it appears. I need help to understand this matter, and if you can provide an image, it will be really useful.

python: is there any way to use natural language processing (NLP) to transform strings into integers?

I saw some code examples to transform strings, like "four" into an integer 4, but it was always quite manual. Is there any more automatic way to do this using NLP?

One thing I noticed when I did the test below was that the spacyrecognize "four" and "4" as numbers, which is a good start, but can you use this to transform one type into another? I don't understand much about natural language processing, so I don't know exactly what name the technique would be responsible for.

nlp = spacy.load("pt")

doc = nlp("quatro vídeos")
for token in doc:
    print(token.text, token.pos_, token.dep_)
# retorna 
# quatro NUM nummod
# vídeos SYM ROOT

doc = nlp("4 vídeos")
for token in doc:
    print(token.text, token.pos_, token.dep_)
# retorna 
# 4 NUM nummod
# vídeos SYM ROOT

Thank you

What is a good introduction to the intermediate book on image processing and analysis and graphics in Mathematica 12?

Thank you for contributing a response to Mathematica Stack Exchange!

  • Please make sure answer the question. Provide details and share your research!

But avoid

  • Ask for help, clarifications or respond to other answers.
  • Make statements based on opinion; Support them with references or personal experience.

Use MathJax to format equations. MathJax reference.

For more information, see our tips on how to write excellent answers.

sql server – Data processing / transfer tool

To specify the context: I am quite fluent in SQL, but I need for a particular project a tool to design data processing scripts. The projects have a database that is filled with two other databases. To do this, I currently use a Python script that retrieves / formats / distributes data. The script runs every 5 minutes with a cron task. So far it's fine.

I would like to have a tool that can help me do this a bit more professionally. Here are the requirements:

  • the tool should be able to use ODBC sources, as well as MySQL / MariaDB / MSSQL
  • the tool should offer the possibility to process / format the data before saving
  • the tool should offer the possibility of using python (or another language such as R for example) to further process the data
  • All this must be done using a GUI
  • the tool should run, if possible, on macOS and Windows
  • it is possible, it must be open source / free

I tried to search for myself, but there are so many applications that seem to do the job …

Thank you very much for your invaluable help.