current position：Home>Bilinear interpolation algorithm for Python OpenCV image, the most detailed algorithm description in the whole network
Bilinear interpolation algorithm for Python OpenCV image, the most detailed algorithm description in the whole network
2022-01-30 05:10:15 【Dream eraser】
Little knowledge , Great challenge ！ This article is participating in 「 A programmer must have a little knowledge 」 Creative activities
This article has participated in 「 Digging force Star Program 」 , Win a creative gift bag , Challenge creation incentive fund .
Python OpenCV 365 Day study plan , Go into the field of image with the eraser . This blog is the third in this series 42 piece .
This blog realizes the compilation of bilinear interpolation algorithm , By the way, revise The last blog nearest neighbor interpolation algorithm is finally implemented and OpenCV The built-in parameters provided are inconsistent . There's another problem , It's the speed of execution , This problem is solved after learning bilinear interpolation algorithm .
Bilinear interpolation algorithm of image
Bilinear interpolation algorithm is a better image scaling algorithm , It makes use of the four real pixel values around the virtual point in the source image , Determine a pixel value in the target image according to the weight .
First extract some principled descriptions ： For a target pixel , The virtual coordinates of the source image can be obtained by reverse transformation , The probability is the floating-point coordinates , The format is
j Is the integer part ,
v It's a fraction , Value
[0,1), At this time, in the source image
(i+u,j+v) It can be determined by the coordinates of the four surrounding pixels
(i+1,j+1) Obtained by calculation , That is, there is a formula ：
f(i+u,j+v) = (1-u)(1-v)f(i,j) + (1-u)vf(i,j+1) + u(1-v)f(i+1,j) + uvf(i+1,j+1)
The transformation of this step has been omitted a lot , The eraser also consulted a lot of information , Next, I'll add . First draw a picture to help understand ~
First, in the X Two linear interpolation in the direction , And then in Y In the direction of the interpolation calculation .
Before calculating , It's time to add knowledge , It's called linear interpolation , Known data and , To calculate Somewhere in the interval x On a straight line y value , The formula is as follows ：
The formula is deformed to obtain ：
After the transformation, it will probably wait for and Distance as a weight , be used for and A weighted , Bilinear interpolation is linear interpolation in two directions .
Continue to look at the picture above , At point 1 With the point 2 Look for a point in the interval , According to the formula ：
The interpolation point 1 =
The same algorithm obtains interpolation points 2：
The interpolation point 2 =
The next in Y Linear interpolation calculation of direction ：
Expand the above formula , You can get the final result , This is not very difficult , Just be careful when writing and reading ：
This formula can be further simplified , Because the interpolation between two adjacent points is 1, So simplify it as follows ：
Bring the coordinates of all points into
take (x,y) Replace with the initial wording
(i+u,j+v) , The other coordinates are spot 1~ spot 4 Respectively ：
(i+1,j+1) , Bring in the above formula , The change results are shown in ：
Don't faint , It is estimated that this is the clearest conversion mode in the whole network ： So far, it echoes the formula at the beginning of this blog .
So the point deduced from the target image , It can be calculated by the coordinates of four points , The in front of each coordinate is called weight , Suppose there is such a pixel whose coordinates are
(1,1), The coordinates obtained in the source diagram are
(0.75,0.75), Because floating point coordinates cannot exist in the image , So get the four surrounding coordinates, which are
(1,1) lately , therefore
(1,1) The point has the greatest effect on the color of the pixel , Corresponding
(1,1) The point corresponding to the point is
f(i+1,i+1) , The coefficient weight in front of this variable is
0.75*0.75 , The result is the biggest , This explanation is explained by real data .
After getting the calculation method , Bilinear interpolation algorithm can be realized through code .
First through the built-in scaling function , Test the run time ：
if __name__ == '__main__': src = cv2.imread('./t.png') start = time.time() dst = cv2.resize(src, (600, 600)) print(' Built in function run time ：%f' % (time.time() - start)) cv2.imshow('src', src) cv2.imshow('dst', dst) cv2.waitKey() Copy code
The time obtained is
Built in function run time ：0.002000 , Very fast .
The next step is to verify the self writing function , I wrote the description of the code in the comments , You can study , Pay attention to the application of the formula
import cv2 import numpy as np import time def resize_demo(src, new_size): # The width and height of the target image dst_h, dst_w = new_size # The width and height of the source image src_h, src_w = src.shape[:2] # If the image size is consistent , Just copy and return directly if src_h == dst_h and src_w == dst_w: return src.copy() # Calculate scale scale_x = float(src_w) / dst_w scale_y = float(src_h) / dst_h # Traverse the target image dst = np.zeros((dst_h, dst_w, 3), dtype=np.uint8) # return dst # Cycle the channel # for n in range(3): # Yes height loop for dst_y in range(dst_h): # Yes width loop for dst_x in range(dst_w): # The coordinates of the target on the source src_x = dst_x * scale_x src_y = dst_y * scale_y # Calculate on the source diagram 4 The location of two nearest neighbors # i,j i = int(np.floor(src_x)) j = int(np.floor(src_y)) u = src_x-i v = src_y-j if j == src_h-1: j = src_h-2 if i == src_w-1: i = src_h-2 # f(i+u,j+v) = (1-u)(1-v)f(i,j) + (1-u)vf(i,j+1) + u(1-v)f(i+1,j) + uvf(i+1,j+1) dst[dst_y, dst_x] = (1-u)*(1-v)*src[j, i]+u*(1-v) * \ src[j+1, i] + (1-u)*v*src[j, i+1]+u*v*src[j+1, i+1] # dst[dst_y, dst_x] = 0.25*src[j, i]+0.25 * \ # src[j+1, i] + 0.25*src[j, i+1]+0.25*src[j+1, i+1] # dst[dst_y,dst_x,n] = 255 return dst if __name__ == '__main__': src = cv2.imread('./t.png') start = time.time() dst = resize_demo(src, (500, 600)) print(' Self writing function running time ：%f' % (time.time() - start)) cv2.imshow('src', src) cv2.imshow('dst', dst) cv2.waitKey() Copy code
Code running consumes
2s many , It really takes time .
I hope today's 1 You get something in an hour , I'll see you on our next blog ~
author[Dream eraser],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Python collects and monitors system data -- psutil
- Python chat room (Tkinter writing interface, streaming, socket to realize private chat, group chat, check chat records, Mysql to store data)
- Learning this Python library can reduce at least 100 lines of code
- leetcode 67. Add Binary（python）
- Regular re parameter replacement of Python 3 interface automation test framework
- V. pandas based on Python
- Only 15 lines of code is needed for face detection! (using Python and openCV)
- [Python crawler Sao operation] you can crawl Sirius cinema movies without paying
- leetcode 69. Sqrt(x)（python）
- Teach you to read the source code of Cpython (I)
guess what you like
Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
leetcode 88. Merge Sorted Array（python）
Don't you know more about a python library before the end of 2021?
Python crawler web page parsing artifact XPath quick start teaching!!!
Use Python and OpenCV to watermark the image
String and related methods of Python data type introduction
Heapq module of Python module
Introduction to beautiful soup of Python crawler weapon, detailed explanation, actual combat summary!!!
Event loop of Python collaboration series
Django docking pin login system
- [recalling the 1970s] using Python to repair the wonderful memories of parents' generation, black-and-white photos become color photos
- You used to know Python advanced
- Pyinstaller package Python project
- 2021 IEEE programming language rankings: Python tops the list!
- Implementation of Python automatic test control
- Python advanced: [Baidu translation reverse] graphic and video teaching!!!
- Do you know the fuzzy semantics in Python syntax?
- [Python from introduction to mastery] (XXVII) learn more about pilot!
- Playing excel office automation with Python
- Some applications of heapq module of Python module
- Python and go languages are so popular, which is more suitable for you?
- Python practical skills task segmentation
- Python simulated Login, numpy module, python simulated epidemic spread
- Python opencv contour discovery function based on image edge extraction
- Application of Hoff circle detection in Python opencv
- Python reptile test ox knife (I)
- Day 1: learn the Django framework of Python development
- django -- minio_ S3 file storage service
- [algorithm learning] 02.03 Delete intermediate nodes (Java / C / C + + / Python / go)
- Similarities and differences of five pandas combinatorial functions
- Learning in Python + opencv -- extracting corners
- Python beginner's eighth day ()
- Necessary knowledge of Python: take you to learn regular expressions from zero
- Get your girlfriend's chat records with Python and solve the paranoia with one move
- My new book "Python 3 web crawler development practice (Second Edition)" has been recommended by the father of Python!
- From zero to familiarity, it will take you to master the use of Python len() function
- Python type hint type annotation guide
- leetcode 108. Convert Sorted Array to Binary Search Tree（python）
- For the geometric transformation of Python OpenCV image, let's first talk about the extraordinary resize function
- leetcode 701. Insert into a Binary Search Tree （python）
- For another 3 days, I sorted out 80 Python datetime examples, which must be collected!
- Python crawler actual combat | using multithreading to crawl lol HD Wallpaper
- Complete a python game in 28 minutes, "customer service play over the president card"
- The universal Python praise machine (commonly known as the brushing machine) in the whole network. Do you want to know the principle? After reading this article, you can write one yourself
- How does Python compare file differences between two paths
- Common OS operations for Python
- [Python data structure series] linear table - explanation of knowledge points + code implementation
- How Python parses web pages using BS4
- How do Python Network requests pass parameters
- Python core programming - decorator