Finding size of the object in python (OpenCV)?
It is primitive method. Convert to grayscale and check which points have value bigger then some "bright" color ie. 21 and it gives array True/False
- using .any(axis=0)
you can reduce every row to single value, using .any(axis=1)
you can reduce every column to single value and then using sum()
you can count how many True
was in any row or column (because True/False
is converted to 1/0
)
import cv2
img = cv2.imread('image.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#print(img)
print('height, width, color:', img.shape)
#cv2.imshow('image', img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
print('width:', sum((img > 21).any(axis=0)))
print('height:', sum((img > 21).any(axis=1)))
For your image it gives me
width: 19
height: 27
For my image (below) it gives me
width: 23
height: 128
EDIT: Version with small change.
I set mask = (img > 21)
to
calculate size
create Black&White image which better shows which points are
used to calculate size.
BTW: code ~mask
inverts mask (convert True
to False
and False
to True
). It can be used also to invert image - ~img
- to create negative for RGB, Grayscale or B&W.
Code:
import cv2
for filename in ['image-1.png', 'image-2.png']:
img = cv2.imread(filename)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print('height, width, color:', img.shape)
mask = (img > 21)
# display size
print(' width:', sum( mask.any(axis=0) ))
print('height:', sum( mask.any(axis=1) ))
# create Black&White version
img[ mask ] = 255 # set white
img[ ~mask ] = 0 # set black
# display Black&White version
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# write Black&White version
cv2.imwrite('BW-' + filename, img)
--->
--->
EDIT: The same result using cv2.boundingRect()
instead of sum(mask.any())
- but it still needs img[ mask ] = 255
to create Black&White image.
import cv2
for filename in ['image-1.png', 'image-2.png']:
print('filename:', filename)
img = cv2.imread(filename)
#print('height, width, color:', img.shape)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#print('height, width, color:', img.shape)
mask = (img > 21)
# create Black&White version
img[ mask ] = 255 # set white
img[ ~mask ] = 0 # set black
x, y, width, height = cv2.boundingRect(img)
# display size
print(' width:', width)
print('height:', height)
# display Black&White version
#cv2.imshow('image', img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
# write Black&White version
#cv2.imwrite('BW-' + filename, img)
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html#bounding-rectangle
EDIT: The same result using cv2.boundingRect()
and cv2.threshold()
- so it doesn't need mask
import cv2
for filename in ['image-1.png', 'image-2.png']:
print('filename:', filename)
img = cv2.imread(filename)
#print('height, width, color:', img.shape)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#print('height, width, color:', img.shape)
ret, img = cv2.threshold(img, 21, 255, cv2.THRESH_BINARY) # the same 21 as in `mask = (img > 21)`
x, y, width, height = cv2.boundingRect(img)
# display size
print(' width:', width)
print('height:', height)
# display Black&White version
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# write Black&White version
#cv2.imwrite('BW-' + filename, img)
https://docs.opencv.org/3.4/d7/d4d/tutorial_py_thresholding.html
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html
https://www.learnopencv.com/opencv-threshold-python-cpp/
https://www.geeksforgeeks.org/python-thresholding-techniques-using-opencv-set-1-simple-thresholding/
Find out how much memory is being used by an object in Python
There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).
There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory.
You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).
python. get size of an object
Considering that type(json.dumps(something))==str
you should be able to literally just use len
.
Consider the following
obj = {'content' : 'something goes here'}
json_obj = json.dumps(obj)
json_size = len(json_obj)
serialized_size = len(serialized_object)
if json_size < serialized_size:
print "I'd use the JSON with this..."
Related Topics
"Is" Operator Behaves Unexpectedly With Integers
How to Avoid Having Class Data Shared Among Instances
Strange Result When Removing Item from a List While Iterating Over It
How to Print Without a Newline or Space
Are Dictionaries Ordered in Python 3.6+
How to Remove Duplicates from a List, While Preserving Order
Is There a Difference Between "==" and "Is"
How to Count the Occurrences of a List Item
Is There a Built in Function For String Natural Sort
How to Make Function Decorators and Chain Them Together
What Do Lambda Function Closures Capture
Using Python'S Eval() Vs. Ast.Literal_Eval()
How to Get a Cron Like Scheduler in Python
Drop All Duplicate Rows Across Multiple Columns in Python Pandas