Some summary of usage in Python

Source: Internet
Author: User
Tags readline

Wrote a test demo in Python, which involves some common usage and is now recorded here for easy follow-up review:

1 use of global variables in Python:

Referencing global variables, not requiring golbal declarations, modifying global variables, using the global Declaration, specifically, lists, dictionaries, etc. if you just modify the values of the elements in them, you can use global variables directly, without the need for the Globals declaration.

Global variables are defined outside of all programs, and then used inside the function is divided into two cases, one is to use the value of the global variable, the second is to modify the value of the global variable, the first case will not produce ambiguity, directly use, In the second case, it is possible to create a new variable or a modification to an existing global variable, so you need to add the global declaration. As mentioned above, a list, a dictionary, etc., if you just modify the value of the element, you do not need to declare, direct reference.

2 dictionaries are sorted in reverse order by key,

The sorted return value is a list, and the name value pairs in the original dictionary are converted to tuples in the list, sorted by value only need to swap the index after the lambda with [1]:

Lambda dict_sim:dict_sim[True)

3 NumPy calculates the cos distance between two vectors

Feat_vector = net.blobs[' Color_pool4/3x3_s2 '].data[0]
#print ' Feat_vector is ', feat_vector
Feat_list = Feat_vector.tolist ()
Np_probe_feat = Np.array (feat_list)
VEC1 = Np_probe_feat.astype (' Float64 ')
#print ' Vec1 is ', VEC1
For key in Dict_feat.keys ():
#print ' Dict_feat.keys () is ', Dict_feat[key]
VEC2 = Dict_feat[key].astype (' float64 ')
#print ' vec2 is ', VEC2
dis = Np.dot (vec1,vec2)/(Np.linalg.norm (VEC1) *np.linalg.norm (VEC2))
The 4 string list is converted to a float-type vector, which reads the variable from the file to the vector
WhileTrue:
line = F_feat.readline ()
If line:
Image_name = line[:-1]
Image_feat = F_feat.readline () [1:-2]
Image_feat = Image_feat.strip (). Split ( Image_feat = map (eval, image_feat)
Array_feat = Np.array (image_feat)
#print ' Array_feat is ', Array_feat< Span style= "color: #808080; Font-style:italic ">
#save the image name and its feat into the Glob Al dict
Dict_feat[image_name] = array_feat #no same key, so make no if else
5 pil type of image with CV type is converted to each other
See http://www.mamicode.com/info-detail-1777172.html
http://blog.csdn.net/dcrmg/article/details/ 78147219
 import Cv2 
from PIL import Image
import numpy

image = Image.open (" plane.jpg ")
Image.show ()
img = Cv2.cvtcolor (Numpy.asarray (image), Cv2. COLOR_RGB2BGR)
Cv2.imshow ( "OpenCV", img)
Cv2.waitkey ()

 import Cv2 
from PIL import Image
import numpy

img = cv2.imread (" plane.jpg ")
Cv2.imshow (" OpenCV ", IMG)
Image = Image.fromarray (Cv2.cvtcolor (IMG, Cv2. COLOR_BGR2RGB)
Image.show ()
Cv2.waitkey ()
 
Prob = image.open (filename)
Cv2_prob = Cv2.cvtcolor (Np.asarray (prob), Cv2. COLOR_RGB2BGR)
Prob_constant = Cv2.copymakeborder (Cv2_prob, 10, 10, 10, 10, Cv2. Border_constant, value=border_color) #opecv中的补边操作
Prob_pil = Image.fromarray ( Cv2.cvtcolor (Prob_constant, Cv2. COLOR_BGR2RGB))
Prob_resize = Prob_pil.resize ((int (unit_size_w), int (Unit_size_h)), Image.antialias)

6 writes a vector to a TXT file, I'm going to turn it into a list, then convert the list to a string and write to the file:
Feat_vector = net.blobs[' color_pool4/3x3_s2 '].data[0]
Feat_list = Feat_vector.tolist ()
Wf.write (str (feat_list))

7 Use the PIL library to combine multiple small graphs into a larger picture:
def pinjie (images, prob, filename, param):
target = Image.new (' RGB ', (Unit_size_w * (num_x +1), Unit_size_h * num_y))
Target.paste (prob[0], (unit_size_w * num_x,0, Unit_size_w * (num_x +1), Unit_size_h))
For IInchRange (num_y):
leftup_x =0
leftup_y = Unit_size_h * I
rightdown_x = Unit_size_w
rightdown_y = Unit_size_h * (i +1)
for J in " Span style= "COLOR: #000080" >range (num_x):
Count = j + i * Num_y Target.paste (Images[count), (leftup_x, leftup_y, rightdown_x , rightdown_y))
Leftup_x = leftup_x + unit_size_w
rightdown_x = rightdown_x + unit_size_w
Quality_value = 100
Span style= "color: #808080; Font-style:italic "> Target.save (param + (Filename.strip (). Split (" /')) [-1] + ' _merge.jpg ', quality = quality_value)

Some of the usage summaries in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.