How to get vertices of rotated rectangle? - python

I try smth like this:
def main_rec():
width = random.randint(150, 250)
height = random.randint(150, 250)
angle = rand_angle()
c, s = np.cos(angle), np.sin(angle)
R = np.array(((c, -s), (s, c)))
center = (random.randint(0, 640), random.randint(0, 480))
x1y10 = (center[0] - width / 2, center[1] + height / 2)
x2y20 = (x1y10[0] + width, x1y10[1])
x3y30 = (x2y20[0], x2y20[1] - height)
x4y40 = (x3y30[0] - width, x3y30[1])
x1y1 = (x1y10[0] * R[0][0] + x1y10[1] * R[0][1], x1y10[0] * R[1][0] + x1y10[1] * R[1][1])
x2y2 = (x2y20[0] * R[0][0] + x2y20[1] * R[0][1], x1y10[1] * R[0][1] + x2y20[1] * R[1][1])
x3y3 = (x3y30[0] * R[0][0] + x3y30[1] * R[0][1], x3y30[0] * R[1][0] + x3y30[1] * R[1][1])
x4y4 = (x4y40[0] * R[0][0] + x4y40[1] * R[0][1], x4y40[1] * R[0][1] + x4y40[1] * R[1][1])
points = [x1y1, x2y2, x3y3, x4y4]
return points, angle / 3.14159 * 180
but I don't know how to set a condition for the corners to be right. I try to use rotation matrix. It makes normal rectangles only for angle = 0

using numpy and rotation matrix code would be:
import numpy as np
import matplotlib.pyplot as plt
def create_rect(width,height,center):
x,y = center
w,h = width,height
return np.array([[x-w/2,y-h/2],
[x+w/2,y-h/2],
[x+w/2,y+h/2],
[x-w/2,y+h/2],
[x-w/2,y-h/2]]).T
width = np.random.randint(150,250)
height = np.random.randint(150,250)
center = (np.random.randint(0, 640), np.random.randint(0, 480))
angle = np.random.randint(0,360)/360.0*2*np.pi
rotmat = np.array([[np.cos(angle),-np.sin(angle)],
[np.sin(angle),np.cos(angle)]])
rect = create_rect(width,height,center)
rot_rect = rotmat # rect
plt.imshow(*rot_rect)

Related

How to calculate the positions of new points after rotating the image around arbitrary axis

Having a dataset of aligned objects, I would like to augment it by applying random rotations with the axis at the center of the object. Below is the rotation representation (left original, right image rotated around the point (xc, yc).
for rotation, I have used the following logic:
import cv2
import random
image_source = cv2.imread('sample.png')
height, width = image_source.shape[:2]
random_angle = random.uniform(90, 90)
yolo_annotation_sample = get_annotation() # this function retrieves yolo annotation
label_id, xc, yc, object_width, object_height = yolo_annotation_sample # e.g. 4, 0.0189, 0.25, 0.0146, 0.00146
center_x = width * xc
center_y = height * yc
left = center_x - (width * object_width) / 2
top = center_y - (height * object_height) / 2
right = left + width * object_width
bottom = top + height * object_height
M = cv2.getRotationMatrix2D((cx, cy), random_angle, 1.0)
image_rotated = cv2.warpAffine(image_source, M, (width, height))
# logic for calculating new point position (doesn't work)
x1_y1 = np.asarray([[left, top]])
x1_y1_new = np.dot(x1_y1, M)
x2_y2 = np.asarray([[right, top]])
x2_y2_new = np.dot(x2_y2, M)
x3_y3 = np.asarray([[right, bottom]])
x3_y3_new = np.dot(x3_y3, M)
x4_y4 = np.asarray([[left, bottom]])
x4_y4_new = np.dot(x4_y4, M)
Does anyone know how to recalculate the point(s) after rotating around the arbitrary point as shown above?
Use cv2.transform(points, M). Points with shape: (4, 1, 2). Full code:
import cv2
import random
import numpy as np
image_source = cv2.imread('sample.png')
height, width = image_source.shape[:2]
random_angle = 40 #random.uniform(90, 90)
yolo_annotation_sample = (4, 0.6189, 0.25, 0.246, 0.0846) # this function retrieves yolo annotation
label_id, xc, yc, object_width, object_height = yolo_annotation_sample
center_x = width * xc
center_y = height * yc
left = center_x - (width * object_width) / 2
top = center_y - (height * object_height) / 2
right = left + width * object_width
bottom = top + height * object_height
cx, cy = width / 2, height / 2
M = cv2.getRotationMatrix2D((cx, cy), random_angle, 1.0)
image_rotated = cv2.warpAffine(image_source, M, (width, height))
# logic for calculating new point position (doesn't work)
bbox_points = [[left, top], [right, top], [right, bottom], [left, bottom]]
bbox_points = np.array(bbox_points).reshape((-1,1,2))
rotated_points = cv2.transform(bbox_points, M) # what you need
cv2.polylines(image_source,[bbox_points.astype(int)],True,(255,100,0), 10)
cv2.polylines(image_rotated,[rotated_points.astype(int)],True,(255,100,0), 10)
cv2.imshow("orig", image_source)
cv2.imshow("rotated", image_rotated)
cv2.waitKey()
Look at [https://en.wikipedia.org/wiki/Transformation_matrix][1]
Once I tried to calculate it myself:
class rotm :
'''set up rotation matrix'''
def __init__(self,axis,angle,unit="radians") :
self.m = scipy.zeros((4,4),scipy.float128)
if unit=="radians" :
angler = angle
else :
angler = math.radians(angle)
pass
if axis=='x' :
self.m[0][0]=1.0
self.m[1][1]=math.cos(angler)
self.m[2][2]=self.m[1][1]
self.m[3][3]=1.0
self.m[1][2]=-math.sin(angler)
self.m[2][1]=-self.m[1][2]
elif axis=='y' :
self.m[0][0]=math.cos(angler)
self.m[1][1]=1.0
self.m[2][2]=self.m[0][0]
self.m[3][3]=1.0
self.m[0][2]=math.sin(angler)
self.m[2][0]=-self.m[0][2]
elif axis=='z' :
self.m[0][0]=math.cos(angler)
self.m[1][1]=self.m[0][0]
self.m[2][2]=1.0
self.m[3][3]=1.0
self.m[0][1]=-math.sin(angler)
self.m[1][0]=-self.m[0][1]
pass
pass
def fPrint(self) :
'''auxiliary function: print transformation matrix '''
print(self.m)
pass
pass #end of rotm class

How to perform effective painting in python?

I want to do a project that displays a planet with continents and climatic zones.
I am currently using PyQt5 for painting, with QPainterPath:
There are two problems:
With this approach, it's hard to define zones inside the continent.
Painting is quite slow (calculations are fast, thanks to numpy).
Minimal code for Path creating way:
import sys
import time
import numpy as np
import math
from PyQt5.QtWidgets import QWidget, QApplication, QSlider
from PyQt5.QtGui import QPainter, QPainterPath, QPen
from PyQt5.QtCore import Qt
class TwoDMap(QWidget):
def __init__(self, size):
super().__init__()
self.size = size
self.W = self.size.width() # width of screen
self.H = self.size.height() # height of screen
self.qp = QPainter()
self.circleRadius = self.H/3
self.pointsAcc = 30 # defines how many points will be between main points
self.interface_start_point = [50, 50]
self.circle_start_x = self.interface_start_point[0] + 100
self.circle_start_y = self.interface_start_point[1] + 200
# vars for converting points from math syster to screen system
self.scrcoord = np.array([self.circle_start_x + self.circleRadius ,
self.circle_start_y + self.circleRadius, 0])
self.scrcoordcoef = np.array([1, -1, 1])
######### Vars for rotatiob ###############
# angles
self.rotation_x = 0
self.rotation_y = 0
self.rotation_z = 0
self.axis_x = np.array([1, 0, 0])
self.axis_y = np.array([0, 1, 0])
self.axis_z = np.array([0, 0, 1])
############################################
# main point of star
points = np.array([
[self.circleRadius, math.pi/10 , -math.pi/10, ],
[self.circleRadius, math.pi/4.5 , math.pi/5.5, ],
[self.circleRadius, math.pi/3 , 0 , ],
[self.circleRadius, math.pi/3 , math.pi/5, ],
[self.circleRadius, math.pi/2 , math.pi/4, ],
[self.circleRadius, math.pi/2.75, math.pi/3, ],
[self.circleRadius, math.pi/2.75, math.pi/2, ],
[self.circleRadius, math.pi/4 , 4*math.pi/10, ],
[self.circleRadius, math.pi/5.5 , 5.5*math.pi/8,],
[self.circleRadius, math.pi/6 , math.pi/3, ],
])
# convert to decart coordinates
self.points = np.apply_along_axis(self.sphericToDecart, 1, points)
self.initUI()
self.showFullScreen()
def initUI(self):
self.setWindowTitle('2DMap')
self.setStyleSheet("background-color: black; color: white; font-size: 20px;")
# sliders for rotating
self.angleScale = 100
self.polz1 = QSlider(Qt.Horizontal, self)
self.polz1.setGeometry(self.interface_start_point[0] + 10, self.interface_start_point[1] + 10, 200, 30)
self.polz1.setRange(int(- 2 * math.pi * self.angleScale), int(2 * math.pi * self.angleScale))
self.polz1.setValue(0)
self.polz1.valueChanged.connect(self.angleChanged)
self.polz2 = QSlider(Qt.Horizontal, self)
self.polz2.setGeometry(self.interface_start_point[0] + 10, self.interface_start_point[1] + 40, 200, 30)
self.polz2.setRange(int(- 2 * math.pi * self.angleScale), int(2 * math.pi * self.angleScale))
self.polz2.setValue(0)
self.polz2.valueChanged.connect(self.angleChanged)
self.polz3 = QSlider(Qt.Horizontal, self)
self.polz3.setGeometry(self.interface_start_point[0] + 10, self.interface_start_point[1] + 70, 200, 30)
self.polz3.setRange(int(- 2 * math.pi * self.angleScale), int(2 * math.pi * self.angleScale))
self.polz3.setValue(0)
self.polz3.valueChanged.connect(self.angleChanged)
def angleChanged(self):
# func for rotating picture with slider
self.rotation_x = self.polz1.value()/(2*self.angleScale)
self.rotation_y = self.polz2.value()/(2*self.angleScale)
self.rotation_z = self.polz3.value()/(2*self.angleScale)
self.update()
def paintEvent(self, e):
self.qp.begin(self)
self.qp.setRenderHints(QPainter.Antialiasing)
self.qp.drawEllipse(int(self.circle_start_x), int(self.circle_start_y), int(self.circleRadius*2), int(self.circleRadius*2))
self.qp.setPen(QPen(Qt.green, 3, Qt.SolidLine))
path_obj = self.getSpherePath(self.getPointsToDraw())
self.qp.drawPath(path_obj)
self.qp.end()
def getPointsToDraw(self):
points: np.ndarray = self.allPointsRotationOffset(self.points)
# preparations for computing points
nw = points
nw2 = np.zeros(points.shape)
nw2[-1:] = points[0]
nw2[:-1] = points[1::1]
crs2 = np.cross(np.cross(nw, nw2), nw)
crs2 = (crs2.T / np.sqrt(np.sum(crs2 * crs2, axis=1)) * self.circleRadius).T
alphas = np.arcsin(np.sqrt(np.sum((nw2 - nw) * (nw2 - nw), axis=1)) / (2 * self.circleRadius)) * 2
# determine the number of points depending on the angle between them
endp = ((self.pointsAcc+1) * (alphas / (np.pi / 2)))
endp: np.ndarray = endp.astype(np.int16)
pnts = [0] * points.shape[0]
for i in range(points.shape[0]):
rngs = range(endp[i]+1) * alphas[i] / endp[i]
rng_cos = np.cos(rngs)
rng_sin = np.sin(rngs)
pnts[i] = self.getInterPoints(nw[i], crs2[i], rng_cos, rng_sin)
return pnts
def getSpherePath(self, allpoints):
# func for creating actual path, that will be drawn on screen
path = QPainterPath()
first_point = True
line_break = False
for points in allpoints: # for all point group
for point in points: # for all points in group
# drawing only points with z > 0
if (point[2] > 0):
if first_point:
# for first point we need to move to it
path.moveTo(point[0], point[1])
first_point = False
if line_break:
# now we have point with z > 0, but before this we had point with z < 0
# that means we need to move to new part
path.moveTo(point[0], point[1])
line_break = False
continue
# connect points (z > 0) with simple line
path.lineTo(point[0], point[1])
else:
# we need to disconect line, because point have z < 0 and must not be shown
line_break = True
return path
def getInterPoints(self, basis_i, basis_j, rng_cos, rng_sin):
# function computes points between two main points
# and covert them to screen coord. system with center on sphere center
arr = np.outer(basis_i, rng_cos) + np.outer(basis_j, rng_sin)
return arr.T * self.scrcoordcoef + self.scrcoord
def allPointsRotationOffset(self, points: np.ndarray) -> np.ndarray:
# Rotate points along axises with angles: rotation_z, rotation_y, rotation_x
rotated_pointsZ = self.kvantRotation(points, self.axis_z, self.rotation_z)
rotated_pointsY = self.kvantRotation(rotated_pointsZ, self.axis_y, self.rotation_y)
rotated_pointsX = self.kvantRotation(rotated_pointsY, self.axis_x, self.rotation_x)
return rotated_pointsX
def kvantRotation(self, p: np.ndarray, u, f):
sin = np.sin(f/2)
Sa = np.cos(f/2)
q = sin * u
qp0 = np.matmul(p, -1 * q)
ABC = np.cross(q, p) + Sa * p
qqp = np.outer(qp0, q)
prm = -1 * np.cross(ABC, q) - qqp
trr = Sa * ABC
ans2 = prm + trr
return ans2
def sphericToDecart(self, point):
# Convert points from spheric system to decart system
xyz = np.array([
math.sin(point[1]) * math.cos(point[2]),
math.sin(point[1]) * math.sin(point[2]),
math.cos(point[1])
]) * point[0]
return xyz
def start():
app = QApplication(sys.argv)
ex = TwoDMap(app.primaryScreen().size())
app.exec_()
if __name__ == '__main__':
start()
So I tried another method: using triangles for painting continents:
But this approach is MUCH slower than I thought it would be and slower than the previous method.
Code for triangles:
class Example(QWidget):
def __init__(self):
super().__init__()
self.W = 800
self.H = 800
self.CoF = 50
self.dx = 0
self.initUI()
def initUI(self):
self.setGeometry(50, 50, self.W, self.H)
self.setWindowTitle('Zamo')
self.poligons = []
self.poligons_points = []
self.triangleZam()
self.show()
#profile
def paintEvent(self, e):
start = time.time()
qp = QPainter()
qp.begin(self)
qp.setRenderHints(QPainter.Antialiasing)
pointsF = [
QPoint(430 - 300 + 200, 370 - 300 + 200),
QPoint(440 - 300 + 200, 500 - 300 + 200),
QPoint(260 - 300 + 200, 550 - 300 + 200),
QPoint(420 - 300 + 200, 600 - 300 + 200),
QPoint(420 - 300 + 200, 800 - 300 + 200),
QPoint(530 - 300 + 200, 640 - 300 + 200),
QPoint(680 - 300 + 200, 740 - 300 + 200),
QPoint(630 - 300 + 200, 560 - 300 + 200),
QPoint(720 - 300 + 200, 430 - 300 + 200),
QPoint(570 - 300 + 200, 450 - 300 + 200),
]
main_poli = QPolygon(pointsF)
main_rect: QRect = main_poli.boundingRect()
qp.setBrush(Qt.lightGray)
qp.setPen(QPen(QColor(0, 0, 0, 255), 1, Qt.SolidLine)) # Qt.lightGray QColor(0, 0, 0, 0)
# self.poligons - list of QPoligon's
# self.poligons_points - list of point of poligons (used for optimization)
# main_poli - star
# main_rect - QRect, bounding the star
for i in range(len(self.poligons)):
qp.setBrush(Qt.lightGray)
if main_rect.contains(self.poligons_points[i][0]): # if triangle inside the Rect, then check for intersecting
if main_poli.intersects(self.poligons[i]):
qp.setBrush(Qt.green)
qp.drawPolygon(self.poligons[i])
qp.setBrush(QColor(0, 0, 0, 0))
qp.setPen(QPen(QColor(255, 0, 0, 150), 1, Qt.SolidLine))
qp.drawPolygon(main_poli)
qp.end()
print(time.time() - start)
def triangleZam(self):
r = int(self.W/self.CoF)
midDot = r / np.sqrt(3)
a, b = 0 - r, 0
c, d = r/2 - r, midDot
e, f = r - r, 0
for j in range(int(self.H/midDot + 1)):
a = 0 - r / (j % 2 + 1)
c = r / 2 - r / (j % 2 + 1)
e = r - r / (j % 2 + 1)
for i in range(int(self.CoF + 1)):
points = QPolygon([QPoint(a, b),QPoint(c, d),QPoint(e, f)])
#qp.setBrush(Qt.darkGray)
points2 = QPolygon([QPoint(c, d),QPoint(e, f),QPoint(c+r, d)])
self.poligons.append(points)
self.poligons.append(points2)
self.poligons_points.append([QPoint(a, b),QPoint(c, d),QPoint(e, f)])
self.poligons_points.append([QPoint(c, d),QPoint(e, f),QPoint(c+r, d)])
a = a + r
c = c + r
e = e + r
b = b + midDot
d = d + midDot
f = f + midDot
So, my question is: is there some way to achieve faster painting in python (algorithms, libraries)? Or maybe is there some resource I can study about 2D rendering basics?

Read the analog clock image and display the time using the opencv python [duplicate]

This question already has an answer here:
I have using opencv python form converting the analog clock to a digital data for the hours and minutes but I need it to show for seconds too
(1 answer)
Closed 1 year ago.
I tried to read the analog clock image and display the time using the digital image using the opencv python, I have done for reading the hours and minutes by separating the hours and minutes hand from the image using HoughLineP() using opencv but I am unable to separate the seconds hand from the image, Here is the code I am working with Please help me to separate the Seconds hand and to read the seconds values
import cv2
import math
import numpy as np
import matplotlib.pyplot as plt.
from math import sqrt, acos, degrees
import tkinter as tk
kernel = np.ones((5,5),np.uint8)
img = cv2.imread('input3.jpg')
ret, thresh = cv2.threshold(gray_img, 50, 255, cv2.THRESH_BINARY)
height, width = gray_img.shape
mask = np.zeros((height,width), np.uint8)
edges = cv2.Canny(thresh, 100, 200)
cimg=cv2.cvtColor(gray_img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(gray_img, cv2.HOUGH_GRADIENT, 1.2, 100)
for i in circles[0,:]:
# print(i) # -> [429.00003 240.6 226.20001]
i[2] = i[2] + 4
# used to detect the circle in the image
cv2.circle(mask, (int(i[0]), int(i[1])), int(i[2]), (255,255,255), thickness=-1)
masked_data = cv2.bitwise_and(img, img, mask=mask)
_,thresh = cv2.threshold(mask,1,255,cv2.THRESH_BINARY)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# Crop masked_data
crop = masked_data[y + 30 : y + h - 30, x + 30 : x + w - 30
i=crop
height, width, channels = i.shape
ret, mask = cv2.threshold(i, 10, 255, cv2.THRESH_BINARY)
edges = cv2.Canny(i,100,200)
kernel = np.ones((11,11),np.uint8)
kernel1 = np.ones((13,13),np.uint8)
edges = cv2.dilate(edges,kernel,iterations = 1)
edges = cv2.erode(edges,kernel1,iterations = 1)
minLineLength = 1000
maxLineGap = 10
lines = cv2.HoughLinesP(edges,
1,
np.pi/180,
15,
minLineLength,
maxLineGap)
l=[]
# l -> long, s -> short
xl1, xl2, yl1, yl2 = 0, 0, 0 , 0
xs1, xs2, ys1, ys2=0, 0, 0 , 0
for line in lines:
# getting the values from the line
x1, y1, x2, y2 = line[0]
dx = x2 - x1
if(dx<0):
dx = dx * -1
dy = y2 - y1
if(dy < 0):
dy = dy * -1
hypo = sqrt(dx ** 2 + dy ** 2 )
l.append(hypo)
a=len(l) # -> 295
l.sort(reverse=True)
m=0
h=0
for f in range(a):
for line in lines:
# getting the values from the line
x1, y1, x2, y2 = line[0]
dx = x2 - x1
if(dx < 0):
dx = dx * -1
dy = y2 - y1
if(dy < 0):
dy = dy * -1
hypo2 = sqrt(dx ** 2 + dy ** 2 )
if(hypo2 == l[0]):
m = hypo2
xl1 = x1
xl2 = x2
yl1 = y1
yl2 = y2
# getting line region
cv2.line(crop, (xl1, yl1), (xl2, yl2), (255, 0, 0), 3)
if(m==l[0]):
if(hypo2 ==l[f]):
if((sqrt((xl2 - x2)**2 + (yl2 - y2)**2)) > 20):
if((sqrt((xl1 - x1)**2 + (yl1 - y1)**2))>20):
xs1 = x1
xs2 = x2
ys1 = y1
ys2 = y2
# getting line region
cv2.line(crop, (xs1, ys1), (xs2, ys2), (0, 255, 0), 3)
h=1
break
if(h==1):
break
xcenter = int(width / 2)
ycenter = int(height / 2)
hour1 = abs(xcenter - xs1)
hour2 = abs(xcenter - xs2)
if(hour1 > hour2):
xhour = xs1
yhour = ys1
else:
xhour = xs2
yhour = ys2
min1 = abs(xcenter - xl1)
min2 = abs(xcenter - xl2)
if(min1 > min2):
xmin = xl1
ymin = yl1
else:
xmin = xl2
ymin = yl2
l1 = sqrt( ((xcenter - xhour) ** 2) + ((ycenter - yhour) ** 2) )
l2 = ycenter
l3 = sqrt( ((xcenter - xhour) ** 2) + ((0 - yhour) ** 2) )
cos_theta_hour = ( ( (l1) ** 2 ) + ( (l2) ** 2 ) - ( (l3) ** 2) ) / ( 2 * (l1) * (l2) )
theta_hours_radian = acos(cos_theta_hour)
theta_hours = math.degrees(theta_hours_radian)
if(xhour > xcenter):
right=1
else:
right=0
if(right==1):
hour = int(theta_hours / (6*5))
if(right==0):
hour = 12 - (int(theta_hours / (6*5)))
if(hour==0):
hour=12
l1 = sqrt( ((xcenter - xmin) ** 2) + ((ycenter - ymin) ** 2) )
l2 = ycenter
l3 = sqrt( ((xcenter - xmin) ** 2) + ((0 - ymin) ** 2) )
cos_theta_min = ( ( (l1) ** 2 ) + ( (l2) ** 2 ) - ( (l3) ** 2) ) / ( 2 * (l1) * (l2) )
theta_min_radian = acos(cos_theta_min)
theta_min = math.degrees(theta_min_radian)
if(xmin > xcenter):
right=1
else:
right=0
if(right==1):
minute = int(theta_min / ((6*5)/5))
if(right==0):
minute = 60 - (int(theta_min / ((6*5)/5)))
if(xmin == xcenter):
minutes=30
if (minute < 10):
def display():
value = "{}:0{}".format(hour,minute)
digit.config(text = value)
else:
def display():
value = "{}:{}".format(hour,minute)
digit.config(text = value)
canvas = tk.Tk()
canvas.title("Analog to Digital")
canvas.geometry("300x250")
digit = tk.Label(canvas, font=("ds-digital", 65, "bold"), bg="black", fg="blue", bd = 80)
digit.grid(row=0, column = 1)
display()
canvas.mainloop()
Considering that your approach to retrieve the values of hours and minute is successful, here is a simple solution to find the value of seconds.
There are certain properties associated with the second-hand of your clock image which need a little preparation before estimating its value. The first one is the color. Because the hand is colored in red, you have a good leading point on separating it from the rest of the image. If you can mask the red color of the second-hand in the image using the cv2.inRange() function (read more about it here), you'll be left with a clean image of only the second-hand. After that, you can convert it to black and white using cv2.cvtColor() function. Now, the second problem might be the thin line of second-hand. You can solve that using Morphological Transformations. Using the Erosion_ function, you can grow the white area of the image and thicken the second-hand. After that, use whatever method you were using to find the value for minutes and hours hand and you are good to go.

How to rotate image with 180 degree when image angle is not fixed in python?

From given image I want to bring flat surface to 180 degree i.e at the bottom. Following code i have tried..
def get_line(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi / 180, 50)
for rho, theta in lines[0]:
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * (a))
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * (a))
# cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
# print(x1, x2, y1, y2)
cx = int((x1 + x2) / 2)
cy = int((y1 + y2) / 2)
# print("abc",cx, cy)
deg = math.degrees(math.atan2(cx, cy))
print(deg)
# cv2.circle(img,(cx,cy),5,(0,255,0),-1)
cv2.imshow('frame', img)
cv2.waitKey(0)
return cx, cy
def rotation():
img=cv2.imread("pr43.jpg")
cx,cy=get_line(img)
height, width, _ = img.shape
# print(width, height)
xpercent = int(abs((cx / width) * 100))
ypercent = int(abs((cy / height) * 100))
# print ("XPercent",xpercent)
# print("YPercent",ypercent)
# print("xpercent, ypercent", xpercent, ypercent)
if xpercent > 50:
print("point in right palne and vertical")
# Todo: rotate clock by 90*
r = imutils.rotate_bound(img, 90)
cv2.imshow("roatated", r)
cv2.waitKey(0)
elif xpercent > 0 and 0 < ypercent < 50:
print("point in upper left plane and vertical")
# Todo: rotate anti-clock by 90*
r = imutils.rotate_bound(img, -90)
cv2.imshow("roatated", r)
cv2.waitKey(0)
elif xpercent <= 0:
print("point in upper left plane and Horizontal")
# Todo: rotate clock by 180*
r = imutils.rotate_bound(img, 180)
cv2.imshow("roatated", r)
elif xpercent < 50 and ypercent > 50:
print("No rotation needed")
r = img
cv2.imwrite("Output_Image.jpg", r)
Below is my output of the code
From this code I'am getting 50% correct output but the surface is not coming at 180 degree. As i cant keep the image angle static because image angle will vary but i have to bring flat surface to Bottom.

Python: Compute surface area of a cylinder

This is what I have. I need to print the surface area
def compute_surface_area_cylindar(radius, height):
surface_area = 2 * math.pi * r * h + 2 * math.pi * math.pow(r, 2)
return surface_area
radius = input("Radius of circle:")
radius = int(radius)
r = radius
height = input("Height of the cylinder:")
height = int(height)
h = height
Here's how you would do it:
import math # You forgot this
def compute_surface_area_cylindar(radius, height):
surface_area = 2 * math.pi * r * h + 2 * math.pi * math.pow(r, 2)
return surface_area
radius = input("Radius of circle:")
radius = int(radius)
r = radius
height = input("Height of the cylinder:")
height = int(height)
h = height
print compute_surface_area_cylindar(radius,height)
The above code will output the surface area of the cylinder based on radius and height, assuming the formula above is correct.
import math
def compute_surface_area_cylindar(radius, height):
surface_area = 2 * math.pi * radius * height + 2 * math.pi * math.pow(radius, 2)
return surface_area
radius = int(input("Radius of circle:"))
#take this out "radius = int(radius)" and you save a line
#take this out an you save a line "r = radius"
height = int(input("Height of the cylinder:"))
# take this out and you save a line "height = int(height) "
#h = height
print(compute_surface_area_cylindar(radius,height))

Categories

Resources