---
# System prepended metadata

title: 影像處理

---

# 影像處理

### 輸出時間
```
import datetime
starttime = datetime.datetime.now()
```
### 點擊出現該pixel資訊
```
import numpy as np
import cv2

global img
def onMouse(event, x, y, flags, param):
    x, y = y, x
    if(event == cv2.EVENT_LBUTTONUP):
        if img.ndim != 3:
            print("(x,y) = (%d, %d)" % (x, y), end="  ")
            print("Gray-Level = %3d" % img[x, y])
        else:
            print("(x,y) = (%d, %d)" % (x, y), end="  ")
            print("(R, G, B) = (%3d, %3d, %3d)" %
                (img[x, y, 2], img[x, y, 1], img[x, y, 0]))
                
                
                
filename = "Ambassadors_s.jpg"
img = cv2.imread(filename, -1)
cv2.namedWindow(filename)
cv2.setMouseCallback(filename, onMouse)
cv2.imshow(filename, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
### upsampling
```
def image_upsampling( f, sampling_rate ):
	fc=np.repeat(np.repeat(f,sampling_rate,axis=1),sampling_rate,axis=0)
	print(f.shape[0],f.shape[1])
	print(fc.shape[0],fc.shape[1])
	return fc
	
    
    
def main( ):
	img1 = cv2.imread( "Lenna.bmp", -1 )
	img2 = image_upsampling( img1, 2 )	
	cv2.imshow( "Original Image", img1 )
	cv2.imshow( "Downsampling by 2", img2 )					
	cv2.waitKey( 0 )
	cv2.destroyAllWindows()
main( )













```
### 高斯打光$(f(x,y)=e^{\frac{x^2+y^2}{2\sigma^2}})$
```
def image_formation_model( f, r0, c0, sigma ):
	g = f.copy( )
	nr, nc = f.shape[:2]
	r1=r0-np.arange(0,nr)
	c1=np.arange(0,nc)-c0
	[c,r]=np.meshgrid(c1,r1)
	illumination=np.exp( -( c ** 2 + r ** 2 ) /( 2 * sigma * sigma ) )
	#cv2.imshow('sigma',illumination)
	#ill_3d=np.dstack((illumination,illumination,illumination))
	#g=np.uint8(ill_3d*f)
	for k in range( 3 ):
		val =  illumination * f[:,:,k] 
		g[:,:,k] = np.uint8( val )
	return g
    
def main( ):
	img = cv2.imread( "Monet.bmp", -1 )
	nr, nc = img.shape[:2]
	r0 = nr // 2
	c0 = nc // 2
	#r0=100  #光源中心
	#c0=100  #光源中心
	sigma = 400 #打光半徑
	img2 = image_formation_model( img, r0, c0, sigma )
	cv2.imshow( "Original Image", img )
	cv2.imshow( "Image Formation Model", img2 )
	cv2.waitKey( 0 )
	cv2.destroyAllWindows()

main( )
```
### image_quantization(gray)
```
def image_quantization(img, bits):
    img1 = img.copy()
    levels = 2**(8-bits)
    img2 = (np.floor(img1/levels)*levels).astype("uint8")
    return img2

def main():
    filename = "Lenna.bmp"
    img = cv2.imread(filename, -1)
    bits = int(input("input bits:"))
    img1 = image_quantization(img, bits)
    cv2.imshow(filename, img1)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

main()




















```
### image_quantization(color)
```
def image_quantization(img, bits):
    img1 = img.copy()
    levels = 2**(8-bits)
    for i in range(3):
        img1[:,:,i] = (np.floor(img[:,:,i]/levels)*levels).astype("uint8")
    return img1

def main():
    filename = "Baboon.bmp"
    img = cv2.imread(filename, -1)
    bits = int(input("input bits:"))
    img1 = image_quantization(img, 2)
    img2 = image_quantization(img, 3)
    img3 = image_quantization(img, 5)
    img4 = image_quantization(img, 6)
    cv2.imshow("a", img1)
    cv2.imshow("aa", img2)
    cv2.imshow("aaa", img3)
    cv2.imshow("aaaa", img4)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

main()
```
### 內插法
```
img = cv2.imread("book.jpg", -1)
nr1, nc1 = img.shape[:2]
nr2, nc2 = nr1//3, nc1//3
img1 = cv2.resize(img, (nc2, nr2), interpolation=cv2.INTER_NEAREST)
img2 = cv2.resize(img1, (nc1, nr1), interpolation=cv2.INTER_NEAREST)
img3 = cv2.resize(img, (nc2, nr2), interpolation=cv2.INTER_LINEAR)
img3 = cv2.resize(img3, (nc1, nr1), interpolation=cv2.INTER_LINEAR)
img4= cv2.resize(img, (nc2, nr2), interpolation=cv2.INTER_CUBIC)
img4 = cv2.resize(img3, (nc1, nr1), interpolation=cv2.INTER_CUBIC)
cv2.imshow("original", img)
cv2.imshow("NEAREST", img2)
cv2.imshow("bilinear", img3)
cv2.imshow("bicubic", img4)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
### 影像旋轉
```
import numpy as np
import cv2
from math import *

img1 = cv2.imread("lenna.bmp", -1)
nr, nc = img1.shape[:2]
center = (nc / 2, nr / 2)
angle = int(input("input angle:")) % 360
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1)

abs_cos = abs(rotation_matrix[0, 0])
abs_sin = abs(rotation_matrix[0, 1])

bound_w = int(nr * abs_sin + nc * abs_cos)
bound_h = int(nr * abs_cos + nc * abs_sin)

rotation_matrix[0, 2] += bound_w/2 - center[0]
rotation_matrix[1, 2] += bound_h/2 - center[1]


img2 = cv2.warpAffine(img1, rotation_matrix, (bound_w, bound_h))
cv2.imshow("Original Image", img1)
cv2.imshow("Image Rotation", img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
### 影像翻轉
```
img1 = cv2.imread( "Poker.bmp", -1 )
img1=cv2.flip(img,0)//垂直翻轉
img1=cv2.flip(img,1)//水平翻轉
```
### 仿射轉換
```
img1 = cv2.imread( "Poker.bmp", -1 )
nr, nc = img1.shape[:2]
//原本圖的點
pts1 = np.float32([[ 270, 125],[ 160, 165 ], [ 240, 390 ]])
//目標的點
pts2 = np.float32([[ 310, 140],[ 190, 140 ], [ 190, 375 ]])
T = cv2.getAffineTransform( pts1, pts2 )
img2 = cv2.warpAffine( img1, T, ( nc, nr ) )
cv2.imshow( "Original Image", img1 )
cv2.imshow( "Affine Transform", img2 )
cv2.waitKey( 0 )
cv2.imwrite( "O.bmp", img2 )
cv2.destroyAllWindows()
```
### 透視轉換
```
img1 = cv2.imread("Gallery.bmp", -1)
img3 = cv2.imread("book.jpg", -1)
pts1 = np.float32([[0, 0],[0, img3.shape[0]],[
                  img3.shape[1], img3.shape[0]], [img3.shape[1], 0]])

pts2 = np.float32([[795, 350], [795, 690], [1090, 720], [1090, 250]])

T = cv2.getPerspectiveTransform(pts1, pts2)

img2 = cv2.warpPerspective(img3, T, (img1.shape[1], img1.shape[0]))

cv2.fillConvexPoly(img1,pts2.astype(int),0,16)

img2=cv2.add(img1,img2)

cv2.imshow("test", img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
### 高通濾波
```
import cv2
import numpy as np
def Roberts(img):
    kernalx = np.array([[1, 0], [0, -1]])
    kernaly = np.array([[0, 1], [-1, 0]])
    img_kernalx = cv2.filter2D(img, cv2.CV_32F, kernalx)
    img_kernaly = cv2.filter2D(img, cv2.CV_32F, kernaly)
    magnitude=abs(img_kernalx)+abs(img_kernaly)
    g=np.uint8(np.clip(magnitude,0,255))
    return g
    
def Prewitt(img):
    kernalx = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])
    kernaly = np.array([[1, 1, -1], [0, 0, 0], [-1, -1, -1]])
    img_kernalx = cv2.filter2D(img, cv2.CV_32F, kernalx)
    img_kernaly = cv2.filter2D(img, cv2.CV_32F, kernaly)
    magnitude=abs(img_kernalx)+abs(img_kernaly)
    g=np.uint8(np.clip(magnitude,0,255))
    return g
    
def Sobel(img):
    kernalx = cv2.Sobel(img, cv2.CV_16S, 1, 0)
    kernaly = cv2.Sobel(img, cv2.CV_16S, 0, 1)
    absx = cv2.convertScaleAbs(kernalx)
    absy = cv2.convertScaleAbs(kernaly)
    img2 = cv2.addWeighted(absx, 0.5, absy, 0.5, 0)
    return img2
    
def Robinson(img):
    kernalx = np.array([[-1, -1, -1], [1,  -2,  1], [1, 1, 1]])
    kernaly = np.array([[-1, 1, 1], [-1,  -2,  1], [-1, 1, 1]])
    img_kernalx = cv2.filter2D(img, cv2.CV_32F, kernalx)
    img_kernaly = cv2.filter2D(img, cv2.CV_32F, kernaly)
    magnitude=abs(img_kernalx)+abs(img_kernaly)
    g=np.uint8(np.clip(magnitude,0,255))
    return g
    
def Kirsch(img):
    kernalx = np.array([[-5,  -5,  -5], [3,  0, 3], [3, 3, 3]])
    kernaly = np.array([[-5, 3, 3], [-5,  0,  3], [-5, 3, 3]])
    img_kernalx = cv2.filter2D(img, cv2.CV_32F, kernalx)
    img_kernaly = cv2.filter2D(img, cv2.CV_32F, kernaly)
    magnitude=abs(img_kernalx)+abs(img_kernaly)
    g=np.uint8(np.clip(magnitude,0,255))
    return g
    
def Laplacian(img):
    temp = cv2.Laplacian(img, cv2.CV_32F) + 128
    g = np.uint8(np.clip(temp, 0, 255))
    return g
    
def composite_Laplacian(img):##混合拉普拉斯
    kernal = np.array([[0, -1, 0], [-1,  5,  -1], [0, -1, 0]])
    temp = cv2.filter2D(img, cv2.CV_32F, kernal)
    g = np.uint8(np.clip(temp, 0, 255))
    return g
    
img = cv2.imread("Osaka.bmp", -1)
##cv2.imshow("Roberts", Roberts_img)
img2=Robinson(img)
img3=Kirsch(img)
cv2.imshow("Robinson", img2)
cv2.imshow("Kirsch", img3)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
### 高斯濾波 雙邊濾波 非銳化遮罩 中值濾波
```
def Bilateral(img):
    g = cv2.bilateralFilter(img, 5, 50, 50)
    ##cv2.bilateralFilter(img,filter矩陣大小,50,50)
    return g

def GetGaussianKernel2D(ksize, sigma):
    kernelX = cv2.getGaussianKernel(ksize[0], sigma).reshape(ksize[0], 1)
    kernelY = cv2.getGaussianKernel(ksize[1], sigma).reshape(1, ksize[1])
    kernel = kernelX*kernelY
    return kernel
    
def Gaussian(img):
    kernel = GetGaussianKernel2D((3, 3), 1)
    img2 = cv2.filter2D(img, -1, kernel, borderType=cv2.BORDER_DEFAULT)
    return img2

def Unsharp(img,k=1.0):
    ##k>1為高增濾波
    f_avg = cv2.GaussianBlur(img, (3, 3), 0)
    g_mask = (img.astype(int))-(f_avg.astype(int))
    g = np.uint8(np.clip(img+k*g_mask, 0, 255))
    return g

def medianfilter(img):
    img1=cv2.medianBlur(img,3)
    ##cv2.medianBlur(img,filter矩陣大小)
    return img1
```
### beta校正 gamma校正 直方圖等化
```//beta校正
def beta_correction( f, a = 2.0, b = 2.0 ):
	g = np.uint8(( special.betainc( a, b, f/255 ))*255)
	return g
```
```//gamma校正
def gamma_correction( f, gamma = 2.0 ):
	g=(f/255)**gamma
	g=np.uint8(g*255)
	return g
```
```//直方圖等化
img1 = cv2.imread( "Indoor_Over_Exposure.bmp", -1 )
img2 = cv2.equalizeHist(img1)	
cv2.imshow( "Histogram Equalization", img2 )
cv2.waitKey( 0 )
cv2.destroyAllWindows()
```
