Crop an image from x and y position using sorl_thumbnail - django

Python 3 and Django 1.11.15
Hi,
I'm using a plugin which returns an x and y position from an image besides usual image dimensions (width and height). I'd like to crop this image with sorl_thumbnail in Python using x and y position (like image cover on Facebook). I think there is a function, maybe like cropbox(), but I don't understand how it works. Please someone can help me, giving me an example of using this function or another solution to crop an image with these data.
Thanks to all.
Here is a sample of my code in models.py:
from sorl.thumbnail import default as sorl_thumbnail
def as_headline(self):
image = self.image
img_size = "600"
x = 133
y = 0
x2 = 328
y2 = 180
cropbox = (x, y, x2, y2)
return sorl_thumbnail.backend.get_thumbnail("path/to/file.jpg", img_size, cropbox=cropbox).url

Related

How to convert 2d(x,y) cooridinates into 3d(x,y,z) coordinates using python and point cloud?

I have been using this github repo: https://github.com/aim-uofa/AdelaiDepth/blob/main/LeReS/Minist_Test/tools/test_shape.py
To figure out how this piece of code can be used to get x,y,z coordinates:
def reconstruct_3D(depth, f):
"""
Reconstruct depth to 3D pointcloud with the provided focal length.
Return:
pcd: N X 3 array, point cloud
"""
cu = depth.shape[1] / 2
cv = depth.shape[0] / 2
width = depth.shape[1]
height = depth.shape[0]
row = np.arange(0, width, 1)
u = np.array([row for i in np.arange(height)])
col = np.arange(0, height, 1)
v = np.array([col for i in np.arange(width)])
v = v.transpose(1, 0)
I want to use these coordinates to find distance between 2 people in 3D for an object detection model. Does anyone have any advice?
I know how to use 2d images with yolo to figure out distance between 2 people. Based on this link: Compute the centroid of a rectangle in python
My thinking is i can use the bounding boxes to get corners and then find the centroid and do that for 2 bounding boxes of people and use triangulation to find the hypotenuse between the 2 points (which is their distance).
However, i am having a tricky time on how to use a set of 3d coordinates to find distance between 2 people. I can get the relative distance from my 2d model.
By having a 2D depth image and camera's intrinsic matrix, you can convert each pixel to 3D point cloud as:
z = d
x = (u - cx) * z / f
y = (v - cy) * z / f
// where (cx, cy) is the principle point and f is the focal length.
In the meantime, you can use third party library like open3d for doing the same:
xyz = open3d.geometry.create_point_cloud_from_depth_image(depth, intrinsic)

how to make the relationship between velocity and time be linear by ROS-python

I created code which making turtlebot 2 following me depend on detecting my face and chose a value of velocity 0.2 m/s.
my issue is the movement of the robot when disappearing my face suddenly which making turtlebot stops suddenly, I need to make decreasing its velocity gradually like this figure enter link description here
my experience not good in ROS'time
I need it starting the count the seconds from zero every it lost my face.
my issue in my code, Once run the code, the time increase continuously whether it is lost my face or not.in this line
v = self.twist.linear.x = (-0.07 * t + 0.2)
my full code:
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from geometry_msgs.msg import Twist
import cv2, cv_bridge
face_cascade = cv2.CascadeClassifier('/home/redhwan/1/run-webcam/Face-Detect-Demo-by-Ali-master/haarcascade_frontalface_default.xml' )
class Face_detection:
def __init__(self):
self.bridge = cv_bridge.CvBridge()
self.starting_time = rospy.get_rostime().to_sec()
self.save_time = True
self.image_sub = rospy.Subscriber('/usb_cam/image_raw',Image, self.image_callback)
self.cmd_vel_pub = rospy.Publisher('/cmd_vel_mux/input/teleop',Twist, queue_size=1)
self.twist = Twist()
def image_callback(self, msg):
image = self.bridge.imgmsg_to_cv2(msg,desired_encoding='bgr8')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale( gray,scaleFactor=1.1,minNeighbors=5,minSize=(30, 30),flags=cv2.cv2.CASCADE_SCALE_IMAGE)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
self.twist.linear.x = 0.2
self.cmd_vel_pub.publish(self.twist)
cv2.imshow('face ', image)
cv2.waitKey(3)
if(type(faces) == tuple):
if(self.save_time == False):
# self.save_time = False #Condition only the first time
self.starting_time = rospy.get_rostime().to_sec() #save the current time
now = rospy.get_rostime().to_sec()
# self.save_time == False
t = (now - self.starting_time)
print ('t',t)
if t <2.9:
v = self.twist.linear.x = (-0.07 * t + 0.2)
print v
self.cmd_vel_pub.publish(self.twist)
if t >= 2.9:
v = self.twist.linear.x = 0
print v
self.cmd_vel_pub.publish(self.twist)
rospy.init_node('face_detection')
follower = Face_detection()
rospy.spin()
please help me
Thank in advance
If all you need to do it make the movements of turtlebot smoother. You might find that the velocity smoother package will fulfill your needs.
You can install it by running:
sudo apt install ros-kinetic-yocs-velocity-smoother
The node takes raw velocity input and filters it based on acceleration parameters. So you can remap your cmd_velocity_mux output to raw_cmd_vel and remap the smoothed output smooth_cmd_vel to the input going to the turlebot.

the result of density contour plot with histogram2d and matplotlib

i am trying to plot a 2D contour density map using histogram2d, i2d turned the histogram output into contour plot and plotted my data with contourf but i didn't appreciated the result, since it gives me a map with a huge rectangle in the middle.
here's the code i'm usingenter image description here
db = 1
lon_bins = np.linspace(min(lons)-db, max(lons)+db, (max(lons)-min(lons))*100)
lat_bins = np.linspace(min(lats)-db, max(lats)+db, (max(lats)-min(lats))*100)
h, xedges, yedges = (np.histogram2d(lats, lons,[lat_bins, lon_bins])
yi, xi = m(*np.meshgrid(lon_bins, lat_bins))
g = np.zeros(xi.shape)
g[:-1,:-1] = h
g[-1] = g[0] # copy the top row to the bottom
g[:,-1] = g[:,0] # copy the left column to the right
print g.shape,yi.shape,xi.shape
cs = m.contourf(yi, xi, g, cmap='Dark2')
cbar = plt.colorbar(cs, orientation='horizontal')
cbar.set_label('la densite des impacts foudre',size=18)
plt.gcf().set_size_inches(15,15)
plt.show()
And here's the result i got
so my request is how to have a nicer plotting, i don't want to have that rectangle in the middle ,i want my result being more smoothed...any ideas ?
I found the answer of my request,so in order to get rid of that rectangle i added this to my code :
g[g==0.0] = np.nan
which means, the bins that have density equal to 0 wouldn't appear on the plot and it's working fine.

Python Turtle Rectangle Using 2 Corner Coordinates

beginning CS student here. I am trying to have python 2.7 draw a rectangle using a function that only has the turtle object, the upper left corner coordinates, and the lower right corner coordinates as arguments. I know there are simpler way of drawing a rectangle but I am trying to do it only using corner coordinates.
After running my current code I get the following:
TypeError: can't multiply sequence by non-int of type 'float'
I know this is probably something simple but I am having trouble figuring out what I'm doing wrong so any help would be appreciated.
My code is as follows:
from turtlegraphics import Turtle
def drawLine(t1,x1,y1,x2,y2):
t1.setWidth(1)
t1.setColor(0,0,0)
t1.up()
t1.move(x1,y1)
t1.down()
t1.move(x2,y2)
def rectangleSimple(t2,upperLeftPoint,lowerRightPoint):
t2.setWidth(1)
t2.setColor(0,0,0)
t2.up()
t2.move(upperLeftPoint)
t2.down()
t2.setDirection(270)
t2.move(lowerRightPoint[2])
t2.setDirection(0)
t2.move(lowerRightPoint)
t2.setDirection(90)
t2.move(upperLeftPoint[2])
t2.setDirection(180)
t2.move(upperLeftPoint)
def main():
t1 = Turtle()
x1 = 0
y1 = 0
x2 = 50
y2 = 0
drawLine(t1,x1,y1,x2,y2)
t2 = Turtle()
upperLeftPoint = (-100,50)
lowerRightPoint = (100,-50)
rectangleSimple(t2,upperLeftPoint,lowerRightPoint)
main()
I use the turtle module, not turtlegraphics but my guess is these two lines are at issue:
t2.move(lowerRightPoint[2])
t2.move(upperLeftPoint[2])
Your *Point variables are tuples with two values, X & Y, at indexes 0 & 1 but you're accessing the non-existent third value at index 2. There are many different ways to implement what you're trying to do, here's one using the turtle module that comes with Python:
from turtle import Turtle
X, Y = range(2)
def drawLine(t, x1, y1, x2, y2):
t.up()
t.width(1)
t.pencolor(1, 0, 0) # red
t.goto(x1, y1)
t.down()
t.goto(x2, y2)
def rectangleSimple(t, upperLeftPoint, lowerRightPoint):
t.up()
t.width(1)
t.pencolor(0, 1, 0) # green
t.goto(upperLeftPoint)
t.setheading(0) # East
t.down()
t.goto(lowerRightPoint[X], upperLeftPoint[Y])
t.right(90)
t.goto(lowerRightPoint)
t.right(90)
t.goto(upperLeftPoint[X], lowerRightPoint[Y])
t.right(90)
t.goto(upperLeftPoint)
if __name__ == "__main__":
from turtle import done
t1 = Turtle()
drawLine(t1, 0, 0, 50, 0)
t2 = Turtle()
upperLeftPoint = (-100, 50)
lowerRightPoint = (100, -50)
rectangleSimple(t2, upperLeftPoint, lowerRightPoint)
done()

Python 2.7- how to save a picture through tuple or set values?

So I've been using opencv2 and PIL to get pixel values. They're saved as such
(0, 0, 0), (1, 1, 1)
I've tried like 7 different ways to use this data to create an image.
My biggest problem is I can't seem to get putdata to work with my tuple.
I would show code, but my laptop is flat and my code is broken anyway.
Tldr: how to save an image with PIL using pixel values stored in a tuple?
Something like this should work
from PIL import Image
W = 200
H = 200
img = Image.new("RGB", (W, H))
pixel_list = [(i%256,i%256,i%256) for i in range(W*H)]
i_pixel = 0
for x in range(W):
for y in range(H):
img.putpixel((x, y), pixel_list[i_pixel])
i_pixel += 1
img.save('result.png')
With the following result
Note: I read here the following:
In 1.1.6, the above is better written as:
pix = im.load()
for i in range(n):
...
pix[x, y] = value
But I couldn't get that to work.