iT邦幫忙

0

如何用 python 實現照片 block truncation code ?謝謝!

# -*- coding: utf-8 -*-
'''
一、統計所有 pixel 值量
二、計數 pixel 大於平均數的數量
'''
import cv2
import sys
import numpy as np
from tkinter import filedialog
import tkinter as tk
from PIL import ImageTk, Image
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
root = tk.Tk()
radioValue = tk.IntVar()
mediaFrame = tk.Frame(root).pack()
media = tk.Label(mediaFrame)
media.pack()
fig = plt.figure()
plot =fig.add_subplot(111)
canva = FigureCanvasTkAgg(fig,root)
canva.get_tk_widget().pack(side='right')
def cv_imread(filePath):
    cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),-1)
    return cv_img
def oas():
    plt.cla()
    global mode
    try:
        sfname = filedialog.askopenfilename(title='選擇',filetypes=[('All Files','*'),("jpeg files","*.jpg"),("png files","*.png"),("gif files","*.gif")])
        gray = cv2.cvtColor(cv2.resize(cv_imread(sfname),(500,250)),cv2.COLOR_BGR2GRAY)
        y = np.zeros((256))
        sun = 0
        count = 0
        arr = np.array(gray)
        (mean,stddv) = cv2.meanStdDev(gray)
        print(mean)
        print(stddv)
        for i in range(0,gray.shape[0]):
            for j in range(0,gray.shape[1]):
                y[gray[i,j]] += 1
                sun += arr[(i,j)]
                if(arr[i,j]>mean):
                    count += 1
        print(sun,count)
        print((count/(sun-count))**0.5)
        aa = ((count/(sun-count))**0.5)
        print(((sun-count)/count)**0.5)
        bb = (((sun-count)/count)**0.5)
        print(stddv*aa)
        print(stddv*bb)
        print(mean-stddv*aa)
        print(mean+stddv*bb)
        a = mean-stddv*aa
        b = mean+stddv*bb
        ri = gray.shape[0]
        rj = gray.shape[1]
        '''
        s = 0
        c = 0
        for i in range(0,ri,4):
            for j in range(0,rj,4):
                a = arr[i,j]
                s += a 
                if(a>mean):
                    c += 1
        print(s,c)
        print((c/(s-c))**0.5)
        print(((s-c)/c)**0.5)
        '''
        for i in range(0,gray.shape[0]):
            for j in range(0,gray.shape[1]):
                if(arr[(i,j)]>mean):
                    arr[(i,j)]=b
                if(arr[(i,j)]<=mean):
                    arr[(i,j)]=a
        btc=Image.fromarray(arr)
        btc.show()
        plt.bar(np.arange(0,256),y,color="gray",align="center")
        cvphoto = Image.fromarray(gray)
        imgtk = ImageTk.PhotoImage(image=cvphoto)
        media.imgtk = imgtk
        media.configure(image=imgtk)
        canva.draw()
    except:
        print('no open file or no choose mode'+sys.exc_info())
b1 = tk.Button(root, text="打開",command = oas).pack()
root.mainloop()

1 個回答

0
微甜的酸
iT邦新手 3 級 ‧ 2021-04-17 20:30:49

輸入:

輸出:

from keras.datasets.mnist import load_data
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
(data, _), (_, _) = load_data()
df = pd.DataFrame(data[0])
df

plt.axis("off")
plt.imshow(data[0], cmap="gray")

avg = np.average(data[0])
print(avg)

>>> 35.108418367346935

def btc(val):
    return val.where(val > avg, 0).mask(val > avg, 1)

df = df.apply(btc)
plt.imshow(df, cmap="gray")

最後一張忘記去掉x-y軸,請自行腦補<3

@您好!請問您看起來是將照片檔當做 data frame 來處理,真是神乎其技啊! @@

我要發表回答

立即登入回答