miscellaneous

Read and show image

from skimage import io

import cv2

import pandas as pd


#Read in an image

img = io.imread(image_path)

img = cv2.imread(image_path)  #use opencv


#Show an image

plt.imshow(image)


#Read in a CSV to pandas

pd.read_csv(csv_file_path)


repr() function

"The repr() function returns a printable representation of the given object. "

so given a string say  

name = 'hello'

print(repr(name))

The print statement returns 'hello' not hello. Note the extra single quotes come with the result. 

Why this is useful?

When we run e.g. a sql query, we may need to ensemble the query first like

"select * from table where id = '{}' ".format(id)

In this way assuming id is a string, we need the single quotes within the select statement to make it work.

But if id is an integer, the single quotes are not necessary and may even break the query.

with repr(id), it returns with '' if id is string, and returns without '' if it is integer, so the query can be :

"select * from table where id = {}".format(repr(id))

Just a bit easier maybe.


Another good use case is about the escape character \.

say if the id contains '\'. We need \\ to represent one \.

id = '\\abc'

query = "select * from table where id = '{}'".format(id)

print(query)

the select statement string will be wrong, the print result here is select * from table where id = '\abc'

This causes problem when the query is actually executed because there is only one \ left, so it will be considered as an escape character instead of a '\' character.

we need to preserve the '\\' , as the .format has used the \\ once so only one \ is left.

repr() can help to preserve the representation

id = '\\abc'

query = "select * from table where id = {}".format(repr(id))

print(query)

The result will be select * from table where id = '\\abc'

which is correct to be executed.