Raspberry Pi As Speed Camera

Wherever you stand on the topics of road safety and vehicle speed limits it’s probably fair to say that speed cameras are not a universally popular sight on our roads. If you want a heated argument in the pub, throw that one into the mix.

But what if you live in a suburban street used as a so-called “rat run” through route, with drivers regularly flouting the speed limit by a significant margin. Suddenly the issue becomes one of personal safety, and all those arguments from the pub mean very little.

Sample car speed measurements
Sample car speed measurements

[Gregtinkers]’ brother-in-law posted a message on Facebook outlining just that problem, and sadly the local police department lacked the resources to enforce the limit. This set [Gregtinkers] on a path to document the scale of the problem and lend justification to police action, which led him to use OpenCV and the Raspberry Pi camera to make his own speed camera.

The theory of operation is straightforward, the software tracks moving objects along the road in the camera’s field of view, times their traversal, and calculates the resulting speed. The area of the image containing the road is defined by a bounding box, to stop spurious readings from birds or neighbours straying into view.

He provides installation and dependency instructions and a run-down of the software’s operation in his blog post, and the software itself is available on his GitHub account.

We’ve had a lot of OpenCV-based projects but haven’t featured a speed camera before here on Hackaday. But we have had a couple of dubious countermeasures, like that humorous attempt at an SQL injection attack, or a flash-based countermeasure.

102 thoughts on “Raspberry Pi As Speed Camera

  1. This is a pretty awesome and well documented example usage of OpenCV. I might have to give it a try, just for the fun of it. We live on a Cul de sac, so no real concern about speeding here.

    I do find it funny that the project was initiated in response to a post on Facebook about people CONSTANTLY driving 75 in a 25 on the street, but the highest speed in any of the sample images is 36. While that’s probably a little too fast, most people seem to be hovering around the 25-30mph mark which is entirely reasonable.

    His brother sounds old.

        1. Have you considered having your system officially calibrated at the police station, like the other radar and lidar speed guns they use?
          Then the images could potentially be used as evidence when it does catch a reckless driver going 40mph over the limit.

          Also I’m unsure of the compatibility with OpenCV, but have you looked into OpenAlpr as a future feature addition?
          It performs automatic license plate to text conversion.
          Of course more than just that software would be needed, camera (thus pi) positioning matters as well as focus. An outdoor enclosure and everything related to locating it not near your home power/network would be involved, but may make things worth it to actually do something about such drivers.
          (I was hoping “In for a penny in for a pound” may apply due to the nature of the subject)

          Informing the police there is a problem is great. Convincing them it is a higher priority than zero is good too, but sadly they weren’t lying about the under staffed and under resourced problems.
          The more evidence you can provide that is legal and valid, the better!

          1. Brett:
            Yea I suppose that does make since after thinking about it. With a pi there wouldn’t be a realistic way to show the system wasn’t modified after any official calibration.
            I guess the personal calibration would have to do, just to be assured it is working properly and to protect your own reputation. (I assume that is why he has it setup in his own window to test before deploying at his brothers where the problem drivers are meant to be)

          2. Dissy:
            It would be interesting to see what they thought about it though, and it would help bring attention to the speeding problem. One of the issues is the devices used now (radar and lidar) are all line of sight head-on (or tail on), so they may be reluctant to even try something new.

          3. The calibration that’s done for speed radar systems (at least the K55 that I own) is done by the manufacturer, not the police department. It has to be sent out once or twice a year for recertification. There exist tuning forks which will read a certain speed when struck and placed in front of the antenna. These serve as a good daily operational check, but are generally not admissible in court.

            As others have stated, it’s also nigh impossible to prove that the software hasn’t been tampered with or images haven’t been altered after they were generated.

            The best approach with this system is to become the squeaky wheel. It does get the grease, after all. Perhaps before you set it up permanently, bake in a Twitter, Instagram, or Facebook bot. If the speed is above a certain threshold, upload the picture in real time as it is generated. Spread the word on Facebook, tag your local police department in each post.

            Courts have ruled again and again that you have no expectation of privacy on public roads, so post away! Enough public attention and something will have to be done.

          4. @Morgen
            The twitter part especially is a fantastic idea. It could easily spur them into some enforcement. Worst case scenario the police tweet back “please stop spamming us.”

            Also reminds me of a number of video blogs dedicated to bridges that regularly “scalp” trucks.

          5. @morgen If you had to present it in court, you could just show the original video feed and do the math in front of them. I don’t know if the program does it, but it wouldn’t be impossible to have it save the video of each car.

          6. There are many, many things involved here that people don’t understand about law enforcement and especially traffic enforcement with electronic tools such as radar and lidar and speed cameras. There are few to none image only based “photo radars” on public roads. They would have to be approved by the courts as “scientifically sound” evidence. Which means passing Frye. It would not be as hard to do that, except the local traffic court would not be the place to handle it. Also, it’s not so much of “will it work?” as “how it gets speeds wrong, how often, by what amount, what can cause false readings, how often to those events happen in the environment, how much does the software interpret vs. directly measure speed etc, etc, etc…..”. Even “proven” technology such as radar and lidar has had it’s issues. Some places only allow certain radar units, as others are considered inadequate in their accuracy. Lidar was disallowed in ohio for a time because it was never given the Frye test. Lidar isn’t a direct measurement of speed as much as it is a measure of distance traveled vs. time, so that brought up more gottchas than radar, which is considered a direct measurement because it has nothing to do with distance over time, but rather Doppler shift.
            Another problem is that for traffic violations, a lot of jurisdictions consider it as a different type of crime. One that an officer has to observe using either his own eyes or a court approved means. So seeing a local guys video contraption snapping photos and overlaying a speed is not going to generate a ticket.
            Most speed cameras out there that are in use that generate tickets are using either radar, which is getting a speed, and if that speed trips a threshold, a camera is triggered. Some are based on lidar, some are based on inductive loops.
            Often times those things don’t even generate “real tickets” as in, they don’t cost points on your license, but rather cost you a fine and are handled differently than a real, cop issued ticket.
            And ALPR for the normal person would be useless. You don’t have access to DMV records which would give you the owners name. You could say “X car violated the speed N times” but you wouldn’t be able to tie it back to a person unless you know them personally.

            And citizens arrest is NOT applicable to traffic violations. It is not valid in most cases outside of stopping a FELONY that is already in progress. Attempting one is asking for a whole heap of trouble.

            Leave traffic enforcement to the cops…

        2. If that is fruitless, you might talk to your planning commission about blocking off one side. I’ve seen fire gates that have weak plastic locks on them so Emergency Services can plow through it without damage, but it effectively closes the road to everyone else.

    1. Any way you can modify it to capture speed and license plate number from the front? I don’t want to turn anyone in, but would like to know who the speeders are. Many children in my neighborhood.

      1. I guess you won’t be too sad when you knock over and kill a child then. Oh, and the IR LED’s don’t help with handheld radar (and in a lot of cases won’t help with digital cameras with decent IR filters)

        1. Visible light cameras are still sensitive to IR even with filters try aiming a remote control you your cellphone.
          Though in daylight you’d probably need something like the IR laser out of a CD burner which also would be pretty good at outright destroying the image sensor.

  2. Combine this with a large LED display showing the drivers how fast they’re going, and you’ll have a cheap & easy way to make drivers slow down and your street safer :)

  3. A monkey driving while talking on a cell is a lot more dangerous than an attentive driver “speeding”. Slowing down and safety is not exactly correlated – speed limits are a fiction perpetrated by the insurance industry to rack up net profits 1) give out tickets for reasonable speeds and raise rates 2) Reduce payouts in collisions

    In any case it doesn’t matter. The screen caps on the blog show the fastest vehicles, ONE or TWO of dozens, driving over the speed limit to where a cop would put the doughnut down and write a ticket, not the 75MPH the busybody dickhead was claiming. In fact, you now have the reason why the cops ignored the whiner – probably the kind that gets on the phone to complain to them two or three times a day over petty stuff because it upsets his OCD….”short of shooting them” says what kind of a-hole this person is.

    The problem with the democratization of technology is that idiots are being enabled to do socially destructive things, like violating privacy laws, playing law enforcement officer, etc. Just because you can do it (and we could for DECADES, but haven’t), doesn’t mean you should. Look at what idiots with drones have done: https://en.wikipedia.org/wiki/Kyllo_v._United_States Should you build an open source IR camera? Probably not. Will someone? Probably…because they don’t realize the consequences.

    1. I worked for many years as a firefighter and can tell you that excessive speed was a factor in almost all severe accidents that I saw. Granted, there certainly were many incidents where s someone was speeding and didn’t have an accident, but when something bad happens you have to ask if maybe it would have been preventable if the person was able to stop sooner. Again, everyone has different reaction times and skill levels when it comes to operating a vehicle, but I was always surprised when someone would claim they had no fault in an accident although they were speeding because something unexpected had happened. Example: “I might have been going 20mph too fast but that other person swerednoverbinto my Lane. It is clearly her fault.”

      1. Granted you are correct (I have first-responders in my family, I truly don’t doubt you at all), but I seriously doubt that you ever went to an accident where the cause was someone going 36 mph in a 30 zone on a dry, straight, well-lit road. You can, however, get a ticket for doing so. I suppose you have to draw the line somewhere, but that seems a bit ridiculous to me.

        One neighborhood I know of had people constantly complaining about the attendees of a local church there going too fast on the road, so the local police set up a radar trailer. They discovered that the only speeders were the people who lived there, not the church-goers! It turns out that all of the speeding happened during commute times, not during times when the church was in use.

        1. Going 36mph vs 30 probably would not make any difference in 99.99% of the scenarios that will come up.
          The one who cause problems are not the ones who do 6mph over the speed limit but idiots who think it’s ok to do 50 or 60 in a 30mph zone.

      2. The physics is Kinetic Energy = 1/2mass X velocity^2 There are studies agreeing with your experience, especially with pedestrians hit by vehicles- it does not take much extra speed to make death in a pedestrian/vehicle “accident” a certainty.

      3. It’s more likely that the speeding in those accidents was due to the same inattentiveness that led to the accident, but it was not the direct cause. Certainly the speed was a force multiplier that increased the damage caused, but if that was the primary consideration, we’d set the speed limit to 5 MPH.

    2. Until a kid suddenly show off from behind an obstacle. You can be as much attentive as you want but you can’t go against law of physics : your car is heavier than a kid. Think twice before speeding.

      1. Hitting a child at any speed with a car is not going to make things any better unless you were going well under the posted. even at 25 MPH which is the speed limit mostly used in school zones. You can only stop in time for a child you see in time. if a kid darts from between cars and you don’t see them, even @ 25 MPH child = DEAD.
        Teach kids to stay out of the fucking road.

    3. Odd that you link the use of drones to a case about the use of IR cameras, which are soon to be rather common, thereby negating the Court’s reasoning. Even now, insulation sales company reps can drive up and down streets looking for potential business with FLIR products.

      I’ll bet you don’t like burglar alarms either. People playing law enforcement indeed.

    4. Yes, but a monkey with her/his ear on the cell phone SPEEDING is a deadly combination. Further, if a car is driving in public, there is no expectation of privacy (Florida vs. Riley).

      I lived on a similar road to this one. My kids were in elementary school playing in our front yard as the speeders raced by, many of them with cell phones smashed against their ear. If folks use technology wrecklessly and don’t slow down, then citizens must take action, especially if the law doesn’t consider it a priority.

      What’s more important? Driving a few miles more slowly, or running into a kid because you just because your conversation couldn’t wait?

    5. You always here arguments like this from idiots who speed through neighborhoods. Claims like the slow drivers “cause” accidents, because a-holes like you get mad having to slow down. BS. I don’t give an F**** about your “privacy” speeding down the block or through the stop sign by our corner. Aside from the danger to kids chasing balls, dogs, etc, is the fact that all of these self righteous goofballs like you feel the rest of the world should get out of there way. Being courteous would make all driving safer. Idiot.

    6. I agree partially that speed doesn’t cause accidents, 90MPH down a motorway on a clear day is hardly more risky than 70MPH, sure higher speeds can make an accident worse, but they don’t cause the accidents..

      BUT if your driving 45 down a residential street, and a kid walks out between two cars, you won’t stop in time and you kill a kid… if your driving 30, you might still hit them but the kid might survive…

      I always think we should up the motorway limit to 90 but drop to 20 in residential areas…

      1. I would say it’s about 65% more risky. (90^2/70^^2) That’s how much more energy is involved in a collision and how much more distance is required to stop. That seems like a decent amount to me, but then again, I like life.

    7. True inattentive driving is much worse then speeding.
      I also think putting the AC controls in the infotainment center probably a also has contributed to accidents as you have to take you eyes off the road to use it.
      The real problem here though is poor road design which encourages rat running.
      Fault can even fall to the road maintenance who do stupid ass shit like bring a main artery down to one lane and not publish advisories to avoid the route.

    1. Oh please don’t encourage them. I hate those bumps. Buddy of mine in his suburban doesn’t mind, but my old Mercedes’ suspension isn’t meant for this kind of abuse. In some parts of Europe they use other measures to slow traffic: narrow passages, meandering paths or obstacles. Those slow you down according to your and your vehicles current abilities, not how robust your suspension or behind is.

      1. Clearly your Mercedes isn’t meant to be driven in a huge chunk of the USA, if it can’t handle reasonable speed bumps at the posted speed limit. Many rural asphalt, dirt, or rock roads are mile after mile of “speed bumps” for your Mercedes. Next time get a Cadillac or a Lincoln, that’s what farmer Jones drives when he doesn’t want to be mistaken for a yuppie, when they travel to the big city. ;)

    2. Put bumps if you want just don;t expect prompt emergency services either! Oh and the snow is left where the plow may be damaged starting at the beginning of the mandated warning zone. Indot-idiot (Indiana).

    3. The biggest problem with regard to speeding, for my family, is noise. Smack-smack-vrooom all day is not remotely better. It’s already bad enough listening to all the race cars with broken mufflers downshift to start up the small hill.

      Personally, I suspect many people would slow down if someone would just paint narrow lane lines. I tested this theory by parking two cars on either side of the road, which worked until a drunk driver (ex-public official no less) smacked one of them. While speeding.

      1. Any painted lines would have to allow for vehicle width of 8′ or 8.5′ depending on the State. Not even legally parked vehicles allowing that much room aren’t likely to slow many down. Anyone too timid to drive through such a hole at anything over the posted speed limit isn’t a problem. Unless they are to timid to drive between unoccupied vehicles at the speed limit.

        1. Well, I don’t have any recorded figures but it did appear to cut down on the number of 50mph+ drivers. My contention with regard to lane lines is obviously that the wider lanes encourage faster driving. I believe this is corroborated by traffic studies, but I’ll let you look that up. If the standard were 50ft wide, I’d suggest that the standard is wrong. In the same way, if 8.5ft really is the standard perhaps it’s too wide as well.

          As it is we live on an approximately 30ft wide unmarked road. Lines would have at least likely prevented my parked car getting hit last month.

          >

        2. Try setting up an 8′ lane restriction randomly some time. Drivers are fucking retarded when it comes to narrow roads, 8′ is plenty for nearly any passenger vehicle, 8.5 is the maximum width for Commercial vehicles. Meanwhile the lane width is generally 12′

  4. Nice hack.

    Yes, the images are tests from the creator’s own neighborhood, not the one where the speeding is occurring. Like several others here, I’m not a big fan of strictly enforced speed limits. But 75 in a residential 25 zone is way too fast. No matter how good a driver you are, that doesn’t provide sufficient reaction time for darting children. It also presents a road noise issue for residents, and causes undue wear and tear on a road never designed for that service.

    But civic hacking isn’t guaranteed to fix police apathy. For example, police here won’t enforce the noise ordinance because it requires SPL meter measurements, and they claim they don’t have the budget for the meters. Document frequent violations with your own noise meter, they’ll reject the documentation because the meter isn’t calibrated. Get it calibrated, and then they’ll reject it because it isn’t a particular brand and model of meter, and wasn’t calibrated by a particular lab, that they say charges $2,000 for the service. Ask for some proof in writing that these are real requirements, and they just plain get hostile, because best I can tell there is none. They simply don’t want to be bothered with it.

    Maybe [Gregtinker] and his brother-in-law will get lucky, and this will be enough. Otherwise, the only option will be to take the evidence to the local television news, and hope they’ll run a story on it (chances are they will if you sell it right, they love that stuff). That’s usually enough to embarrass the police into doing something – for a while. But they’ll remember. And after that, if it’s possible for them to do even less for you, or inconvenience you in any way, they will.

      1. Which is equally productive, as far as the hack goes. I have a feeling that 75 is few and far between, but that regular speeding by non-residents is a major issue. I’ve lived on such a street and sympathize.

      1. Yours, probably. While I realise that this is a visual thing not audio, having a read of your local “wiretap” laws will probably prove to be sobering.

        For example: making an audio recording in a public space is effectively outlawed most places in the USA for lack of consent from everyone who may be recorded, *especially* if you record a cop, even though it should arguably be the other way around.

        1. What about car dash cams, they record audio and video in public? I’m not in the USA but here the police actually ask people to hand over their footage (make requests using the media) if people were in the vicinity of a serious unsolved crime etc. Same with cameras in homes over looking the street. There is never a problem for the owner of the camera.

        2. Federal, it’s single party consent, further AFAIK the 1st and the 9th circuit have ruled all party consents in public spaces shenanigans, and I’d put $20 on SCOTUS siding with the 1st and the 9th versus any circuit that splits with them. Further, audio recording is completely unneeded for a speed trap.

      2. “Totalitarian regimes” where the individual’s right to privacy (yes, even in public) is valued more than peoples’ rights to put up cameras everywhere.

        There’s a tradeoff here, and there’s a whole range of reasonable compromises. I’d actually rather _not_ be surveilled everywhere I walk. Differnt strokes. Wave to the cameras for me!

          1. To wilbertofdelaware:
            It’s not that simple all around the world, and with world i also mean the area of planet earth around USA and including ISS. I don’t actually think it’s that simple in USA either.

  5. Any way you can modify it to capture speed and license plate number from the front? I don’t want to turn anyone in, but would like to know who the speeders are. Many children in my neighborhood.

    1. If you can determine the owner of a vehicle from looking up their license plate number then you are already an officer of the law, and can give them a speeding ticket. You are also in a state that requires license plates on the front of the car.

      1. That first part isn’t true at all.

        One night at around 2AM a car was speeding down my street and side swiped my car parked on the road in front of my house. He didn’t stop long and kept driving, but the guy next door was outside smoking and saw it happen and wrote down the persons license plate number, then knocked on my door to wake me and let me know.

        I called the police who arrived and took a picture or two of my car, the color of paint left on it, and took the written down license plate number.
        The next day they came back and told me the car was registered to so and so, who they visited and discovered the 17 year old took it out against the (parents? grandparents?) will and was drinking.

        I was provided all the contact information on the cars registration for pressing charges. I am not a law enforcement officer as you claim, but most certainly found out who it was from only a license plate number.

        Perhaps if you are not involved in the crime either way and only recorded the license plate the police may not inform YOU who it was, but they will inform the victim of the crime who it was.

        1. You’re story makes no sense and does not contradict Larry’s comment. “I was provided all the contact information on the cars registration for pressing charges.” – The police are not obligated to provide that information to you, and in most states it is illegal for them to do so. Your insurance company only needs the police report number, and that is all police officers generally give to the victim of hit and run drivers. Hit and run driving is illegal in all US states, and the officer would have gone directly to the offending vehicles owner. If your story is true, then the officer is incompetent.

          1. Not true. You have a right according to federal law to know who committed the crime against you. If a cop runs a license plate in your crime you absolutely have a right to know the owner. This applies in all 50 States and every US possession.

          2. Incorrect Nikk. Anti-Vigilante and Anti-Stalking laws prevent that. It is the same reason credit card companies will refuse to give the information of the person whom stole your credit card number.

    2. Speeding isn’t a crime against “you”. It’s a traffic violation, unless it is over a certain threshold where it becomes “reckless driving”. It still isn’t a crime against you. You do not have access to DVM or BMV records, so license plate numbers are meaningless. Like others have said. Let the police do the police work.

      1. I beg to differ. Speeding, running red lights, changing lanes without signaling, etc. increases the risk of injury to other persons and property. Does any one person have a right to increase the risk of injury or property damage of another by any means? Somehow when we get behind the wheel we forget that our rights end where another’s begins.

  6. It needs another set of cameras close to the road to get the numberplate of the car from either direction. Then have software display the images for review and email off the ones you tick directly to the appropriate authority. Personally I’ve found that just having a obvious camera looking over a road makes the regulars behave a lot better, perhaps it is because in my area you can get your car crushed into a metal brick if you misuse it.

  7. I believe this would be invalid in California as evidence. The law defines an illegal speed trap as enforcement by measuring the target vehicle’s time over a measured-length course.

    Aircraft enforcement in California uses time over a course, but they finesse this by having the aircraft pace the vehicle (they have special planes capable of slow – for a plane – cruising speeds) and time it’s own travel over the fixed course.

  8. That’s a great project and well documented! Might have to try this out.

    Automatically posting the highest offenders to your local police department or neighborhood facebook page would be a fun addition.

  9. Alright, this guy is my new hero, and I am going to reproduce his setup ASAP.

    Here in Berkeley, Stop signs are nothing more than just suggestions. In my neighborhood, people just sail through them at full speed, even on the road in front of my house … which is also a Bicycle Boulevard! Every single day there are near-misses, car-to-bike often resulting in yelling, and car-to-car, resulting in incessant honking.

    My only deterrence so far has been to stand out there with a camera. People are suddenly very willing to stop, so that they can yell at me, throw liquor bottles at me, threaten gun fights, and so on.

    1. Actually I didn’t see that. My inspiration came from the pyimagesearch website, which is an amazing source of Pi camera OpenCV code. The fun of a project like this is creating your own solution – even if someone else has done it before – because that is the only way to really understand a programming technology. My wife doesn’t quite understand why I solve some of the puzzles on my “Daily Brain Games” calendar by writing Ruby code. It is just a way to keep sharp.

    1. I just modified the code to re-initialize the camera after a few hours – just throw the initialization code into a function and call it after x number of hours have passed. Keep in mind you have to close the camera first, so you’ll have to have something like (pseudocode):

      camera_is_initialized = False

      def init_camera()
      if camera_is_initialized:
      camera.close()
      initialize camera
      camera_is_initialized = True

  10. This is a clever and fabulous idea. I live near a beautiful but very high-weekend traffic mountain road, driven regularly by lots of reckless miscreants. Great visual data about what’s happening on our road need to be presented to both the local gendarmerie and their masters before they actually do anything. Our sheriff’s department and our county both need to be embarrassed into action, and then given year-end performance kudos at review time for doing their jobs in enforcement.

  11. Thank you SO much for your post!! I’ve been wanting to do something like this for a while, but was contemplating radar or laser/infrared trips. Your idea is much more simple and works great!! I took your idea (and your code!) and modified it slightly so that it inserts the information into a database (postgres). Now I have the data to crunch and distribute to neighbors and authorities to see how big the problem is in addition to the photos of the cars. AWESOME!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s