2/28/2022

cv2, findContours, find object and print x,y,w,h

Find white color object and print x,y,w,h

see example source code

..

#open image
img = cv2.imread("./test.jpg")

#binary
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)

#contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

#print x,y,w,h for each object
w_list = []
h_list = []
for v in contours:
x,y,w,h = cv2.boundingRect(v)
w_list.append(w)
h_list.append(h)
print(x,y,w,h)

..

66 193 19 14
--
66 171 19 14
--



www.marearts.com

thank you.

๐Ÿ™‡๐Ÿป‍♂️

2/25/2022

list tensor to batch tensor, Pytorch

 4 length list tensor -> 4 x 200 x 200 x 3 tensor

--

print('---- input list tensor')
print('length: ', len(list_torch) )
for g in list_torch:
print(g.shape)
print('---- convert batch tensor')
b = torch.Tensor(4, 200, 200, 3)
torch_batch = torch.cat(grid, out=b)
print(torch_batch.shape)
print('----')

--

output

---- input list tensor
length: 4
torch.Size([1, 200, 200, 3])
torch.Size([1, 200, 200, 3])
torch.Size([1, 200, 200, 3])
torch.Size([1, 200, 200, 3])
---- convert batch tensor
torch.Size([4, 200, 200, 3])
----

--


Thank you.

www.marearts.com

๐Ÿ™‡๐Ÿป‍♂️

crop image with grid, python

Example is to do:

Grid 5x5 and resize 200x200

Each image is numpy type.

--

import cv2
import numpy as np

img = cv2.imread("./data/example.jpg")

def img_to_grid(img, row, col, resize_row, resize_col):
ww = [[i.min(), i.max()] for i in np.array_split(range(img.shape[0]),row)]
hh = [[i.min(), i.max()] for i in np.array_split(range(img.shape[1]),col)]
grid = [img[j:jj,i:ii,:] for j,jj in ww for i,ii in hh]
re_grid=[]
for img in grid:
resized = cv2.resize(img, (resize_row,resize_col), interpolation = cv2.INTER_AREA)
re_grid.append(resized)
return re_grid, len(ww), len(hh)

#------------------------------------
how_many_row, how_many_col = 5, 5
resize_row, resize_col = 200, 200
grid , r,c = img_to_grid(img, how_many_row, how_many_col, resize_row, resize_col)
print(type(grid), type(grid[0]), len(grid), r, c)
#------------------------------------

--


Thank you.

www.marearts.com

๐Ÿ™‡๐Ÿป‍♂️

2/15/2022

module 'keras.optimizers' has no attribute 'Adam'

Use

> tf.keras.optimizers.Adam(learning_rate)

instead of

> keras.optimizers.Adam(learning_rate)



www.marearts.com

2/14/2022

cannot import name 'to_categorical' from 'keras.utils' (/Users/leon/DWF/Dev/FindWalli/find_waldo/env_fw/lib/python3.8/site-packages/keras/utils/__init__.py)

 

use this

> from tensorflow.keras.utils import to_categorical

instead of this

> from keras.utils import to_categorical


Thank you.

www.marearts.com