In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the knowledge of "how to use io and misc modules in SciPy". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Read and write .mat file
If you have some data, or download some interesting data sets on the Internet, which are stored in Matlab's .mat file format, you can use the scipy.io module to read.
Data = scipy.io.loadmat ('test.mat')
In the above code, the data object contains a dictionary whose keys correspond to the variable names saved in the original .mat file. Because these variables are in array format, they can be easily saved to a .mat file.
All you have to do is create a dictionary that contains all the variables you want to save, and then use the savemat () function:
Data = {} data ['x'] = x scipy.io.savemat ('test.mat',data)
Because the above script holds the array x, when read into Matlab, the name of the variable is still x.
2. Save the array as an image
Because we need to manipulate the image and need to use array objects to do the operation, it is useful to save the array directly as image file 1. Many of the images in this book are created in this way.
The imsave () function can be loaded from the scipy.misc module. To save the array im to a file, use the following command:
From scipy.misc import imsave imsave ('test.jpg',im)
The scipy.misc module also contains the famous Lena test image:
Lena = scipy.misc.lena ()
The script returns an array of 512 × 512 grayscale images.
Add: several modules of image preprocessing: PIL, scipy.misc, OpenCV, TensorFlow
1. PIL library
Python Imaging Library (PIL) is a free image processing toolkit provided by PythonWare. It is an image processing module under python. It supports multiple formats and provides powerful graphics and image processing functions.
Although it is not suitable to implement complex image processing algorithms similar to those in MATLAB in this software package, the rapid development ability and object-oriented features of Python make it very suitable for prototype development.
For simple image processing or a large number of simple image processing tasks, python+PIL is a good choice.
From PIL import Image,ImageEnhance # call library im = Image.open ("E:/testdata/01.jpg") # Open picture print (im.format, im.size, im.mode) # print image information''format: image attributes, such as png,jpeg size: image resolution mode: 11-bit pixels, black and white, saved as 8-bit pixels L 8-bit pixels Black and white P 8-bit pixels, using the color palette to map to any other mode RGB 3 × 8-bit pixels, true color RGBA 4 × 8-bit pixels, true color + transparent channel CMYK 4 × 8-bit pixels, color isolated YCbCr 3 × 8-bit pixels Color video format I 32-bit integer pixel F 32-bit floating-point pixel''new_im = im.convert (' L') # convert the image to another mode new_im.save ("E:/testdata/02.png") # Save the image You can change the image format box = (0,0500,500) # determine the size of the copy area (upper left coordinates, lower right coordinates) region = im.crop (box) # copy the picture objects represented by im into region Box region = im.resize ((400,400), Image.ANTIALIAS) # change the image size''function prototype: im.resize (size, filter): size: required size Is a binary: (width, height) filter: for one of NEAREST, BILINEAR, BICUBIC or ANTIALIAS''im_30 = im.rotate (30, Image.NEAREST,1) # the image is rotated 30 degrees counterclockwise. Prototype function: im.rotate (angle,filter=NEAREST, expand=0) ⇒ image angle: the angle value of counterclockwise rotation filter:NEAREST, BILINEAR or one of BICUBIC expand. If true, the output image is large enough. The rotated image can be loaded. If false or default, the output image is the same size as the input image.'' In this case, there are three image objects in rmag _ journal _ b. New_im=Image.merge ("RGB", (rpje gpenh b)) # merge the three channels example = np.random.randint (0meme 255 mineSze = (300pje 300)) # numpy array new_img = Image.fromarray (example, 'RGB') # convert the narray of numpy into Image class The second parameter is mode new_im.show () # display image #-turn an index image into a color image-cmap = [np.random.randint (0255) for x in range (768)] # generate a color hidden map The size needs to be converted from 256*3=768img = img.convert ('P') # to P mode img.putpalette (cmap) # to color the index image img.show () # display image #-Image Enhancement- -# Enhancement enhanceImg = ImageEnhance.Brightness (img) # Image sharpening enhanceImg = ImageEnhance.Sharpness (img) # contrast Enhancement enhanceImg = ImageEnhance.Contrast (img) # Color Enhancement enhanceImg = ImageEnhance.Color (img) enhanceImg.enhance (2.0). Show () # 2.0 means twice the enhancement 1.0 means no enhancement.
Note: Image only receives data of type uint8. If you pass in data of type float32, there will be an error.
2 、 scipy.misc
Python has three very popular libraries in the field of scientific computing, numpy, SciPy and matplotlib.
Numpy is a high-performance library for calculating multi-dimensional arrays. SciPy is built on the basis of numpy. It provides many functions for manipulating numpy arrays. SciPy is a convenient, easy-to-use python toolkit designed for science and engineering. It includes statistics, optimization, integration and linear algebra modules, Fourier transform, signal and image legends, and the solution of ordinary differential variance.
The following is a brief introduction to the application of SciPy in image processing. Of course, it is recommended to use opencv if you specialize in image processing.
From scipy.misc import imread,imsave Imresizeimport scipy.io img = imread ("E:/testdata/01.jpg") # read image print (img) # numpy array img_type = img.dtype # get the data type of the picture print (img_type) # uint8 img_shape = img.shape # get the size of the picture Print (img_shape) # (310 493,3) newimg=imresize (img, (100100)) # Image clipping''function prototype: imresize (arr, size, interp='bilinear', mode=None) arr:ndarray type image size: cropped size Is a tuple interp: interpolation method for the image mode in 'nearest',' lanczos', 'bilinear',' bicubic' or 'cubic' mode:PIL (' playing,'L', etc.) Convert the pattern''imsave ("timg_color.png", newimg) # Save the picture #-load the .mat file using scipy-data = scipy.io.loadmat (' Data.mat') print (data) # generally data is a dictionary type of data 3, OpenCV
OpenCV is an open source computer vision application platform, initiated by the Intel R & D center Russia team, open source BSD certificate, OpenCV's goal is to achieve real-time computer vision, is a cross-platform computer vision library. It has developed rapidly since the date of development, and has received great support and contribution from many companies and industry. Because it is an BSD open source license, it can be used in scientific research and commercial applications free of charge.
OpenCV already includes the following application areas: 2D and 3D feature toolbox, motion estimation, face recognition system, posture recognition, human-computer interaction, mobile robot, motion understanding, object identification, segmentation and recognition, stereo vision, motion tracking, augmented reality (AR technology). Based on the needs of the above functions, OpenCV also includes the following statistics-based machine learning libraries: Boosting algorithm, Decision Tree (decision tree) learning, Gradient Boosting algorithm, EM algorithm (expectation maximization), KNN algorithm, naive Bayesian classification, artificial neural network, random forest, palm vector machine.
Programming language: most of the modules in OpenCV are based on C++, and a few of them are based on C language. The SDK provided by OpenCV already supports C++, Java, Python and other language application development. At present, the newly developed algorithms and module interfaces of OpenCV itself are based on C++. OpenCV-Python uses Numpy, a highly optimized database operation library with MATLAB-style syntax. All OpenCV array structures are converted to Numpy arrays. This also makes it easier to integrate with other libraries that use Numpy, such as SciPy and Matplotlib. Next, let's introduce the core operations of OpenCV:
Import cv2 img = cv2.imread ('Ejjpg') # read the image print (img.shape) print (img) bGramage GLI r = cv2.split (img) # split the image channel img = cv2.merge ((bLI GLO r)) # merge the image channel res=cv2.resize (img, (50J 50) Interpolation=cv2.INTER_CUBIC) # Image scaling''INTER_NEAREST nearest neighbor interpolation INTER_LINEAR bilinear interpolation (default) INTER_AREA uses pixel region relationships for resampling. It may be the preferred method for image extraction because it produces the result of cloud-free texture. But when the image is scaled, it is similar to the INTER_NEAREST method. Bicubic interpolation in INTER_CUBIC 4x4 pixel neighborhood Lanczos interpolation in INTER_LANCZOS4 8x8 pixel neighborhood''img = cv2.cvtColor (img, cv2.COLOR_BGR2RGB) # convert the channel order of reading the image. Cv2 defaults to BGR order, which is converted to RGB. Other software are RGB cv2.imwrite ("hehe.jpg", res) # save image cv2.imshow ("res", res) # display image cv2.waitKey (0) cv2.destroyAllWindows ()
Note: cv2 defaults to BGR order, while other software (PIL, scopy.misc) generally use RGB, so when cv2 and other mixed use, you need to use cv2.cvtColor () to convert the channel.
4. Tf.image module (1) Codec (data types processed in codec are all tf.uint8): tf.image.decode_jpeg (contents, channels=None, ratio=None, fancy_upscaling=None, try_recover_truncated=None, acceptable_fraction=None, name=None) tf.image.encode_jpeg (image, format=None, quality=None, progressive=None, optimize_size=None, chroma_downsampling=None, density_unit=None, x_density=None, y_density=None, xmp_metadata=None, name=None) tf.image.decode_png (contents, channels=None, name=None) tf.image.encode_png (image, compression=None) Name=None) (2) Zoom (the first function is equivalent to the next four These functions accept any data type But the output type is tf.float32): tf.image.resize_images (images, new_height, new_width, method=0) tf.image.resize_area (images, size, name=None) tf.image.resize_bicubic (images, size, name=None) tf.image.resize_bilinear (images, size, name=None) tf.image.resize_nearest_neighbor (images, size, name=None) (3) crop: tf.image.resize_image_with_crop_or_pad (image, target_height) Target_width) tf.image.pad_to_bounding_box (image, offset_height, offset_width, target_height, target_width) tf.image.crop_to_bounding_box (image, offset_height, offset_width, target_height, target_width) tf.image.random_crop (image, size, seed=None, name=None) tf.image.extract_glimpse (input, size, offsets, centered=None, normalized=None, uniform_noise=None Name=None) (4) Flip: tf.image.flip_up_down (image) tf.image.random_flip_up_down (image, seed=None) tf.image.flip_left_right (image) tf.image.random_flip_left_right (image, seed=None) # coding=utf-8 import tensorflow as tf import numpy as np import os from PIL import Image # read data from a file The result is the binary file image_data = tf.gfile.FastGFile ("D:/test/2.jpg", 'rb'). Read () with tf.Session () as sess: # Decode the binary data into a Tensor, and the data type is tf.uint8 img_data = tf.image.decode_jpeg (image_data) print (img_data.eval (). Shape) # resize the image 0: bilinear difference. 1: the nearest neighbor law. 2: bicubic interpolation. 3: area interpolation. Resized = tf.image.resize_images (img_data, [500,500], method=0) # TensorFlow stores data in float32 format after processing the image, which needs to be converted to uint8 to print the picture correctly. Resized = np.asarray (resized.eval (), dtype='uint8') # display picture new_img = Image.fromarray (resized, 'RGB') new_img.show () # encode the image and save the image encoded_image = tf.image.encode_jpeg (resized) print (type (encoded_image)) with tf.gfile.GFile (". / 3.jpg") "wb") as f: f.write (encoded_image.eval ()) (5) data type of converted image: tf.image.convert_image_dtype (image) Dtype)
If the data type passed in is uint8, this function normalizes the pixel values of type uint8 from 0 to 255 to 0-1. If the data type passed in is tf.float32, the function does nothing to the image. If the data type passed in is tf.int32, it becomes a very small decimal after processing.
This is the end of the content of "how to use io and misc modules in SciPy". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.