Monday, November 13, 2017

From One Gun Guy To Another: A Proposal To Reduce Victims In Mass Shootings

Like all of my blog posts, this article gives my personal views and does not represent the views of my employers, past or present. 

Like a lot of folks in America, I grew up around guns. My grandfather and dad taught me to shoot in the clay pits of south Alabama, with a strong focus on safety and responsibility. As I got older, I realized that it was not only a great deal of fun, but a method of effectively protecting myself and my family against folks who might try to do us harm. I take that right and responsibility quite seriously. I practice regularly and have done a lot of reading to educate myself on the implications of using a weapon in self defense. I had a concealed carry permit and carried regularly for years, both at home and when backpacking. I'm a gun guy. I enjoy using them, and I stay ready in case I ever have to use one in defense.

Like a lot of gun guys over the last few years, I've been watching the growing number of mass shootings and struggling with it. Yes, I believe guns in the hands of good guys are a good thing, but how do we balance that against folks who are mentally ill killing or injuring dozens at a time? A lot of gun folks insist it's a people problem, not a gun problem. I argue that it's both. Clearly, mentally ill people must not have access to firearms, to the greatest extent possible. But we all know how hard that is. The background check system fails sometimes, or an ill person simply has someone buy the weapon for them. Sometimes they take a family member's that is not well secured.

So we have a certain number of mentally ill folks that are going to have access to guns. How can we limit the amount of damage they can do without dramatically reducing the freedoms of millions of lawful gun owners? 

We should treat high capacity magazines (>10 rounds) the same way we treat sound suppressors ("silencers"). Existing high capacity magazines should be bought back at fair market value, or the owner acquire the tax stamp and background check. Like suppressors, the penalty for unlawful possession must have serious teeth.

To buy a suppressor, you are subjected to an extensive background check, more so than buying a firearm. For each suppressor you buy, you have to buy a tax stamp, at a cost that is affordable if someone really wants or needs it, but high enough to make it painful to buy a lot of them.  The current cost for the stamp, per suppressor, is $200.

Here are the reasons why this is an effective strategy.

1) It will dramatically reduce the number available to an attacker. Only people who really need them will keep them, and those folks will pass a more stringent background check. They WILL be available to those who need them, though, in modest number.

2) Your kids are probably receiving some form of armed intruder response training in school. I've gotten two variants of it in the workplace. They teach you to run, hide, and as a last option, to wait until the attacker is reloading, and fight. You are trained to throw things, from books to fire extinguishers, and to gang up on the attacker to immobilize him.

If an attacker has a collection of 30 round magazines, pauses to reload don't happen very often. If the magazine capacity is limited to ten rounds, the victims get two additional windows of opportunity per magazine in which to flee or fight. 

3) If someone is planning an attack and tries to accumulate a lot of them, it will be noticed.

4) It effectively limits the number of rounds an attacker can easily carry which are ready to fire.

The existing magazines that were being registered would require serialization. A system would need to be created to allow a worn magazine to be exchanged for a new one without requiring another stamp, and the worn one destroyed.

Undoubtedly, you are raising concerns. They are probably the reactions that I tend to have to any proposed gun control too. 

"The bad guys won't turn theirs in, so it won't help." 

A lot of guns used in mass shootings are obtained legally by the shooter or through family members. Making high capacity magazines harder to obtain will make it more likely that a shooter won't have a pile of those magazines on them when they commit their crime. 

"I can change a magazine really quickly. It won't make a difference."

For some people who are extensively trained to use guns under pressure- military, for example - that's probably reasonably true. For those of us who spend our days in offices, though, changing a magazine at the range doesn't translate to doing it while people are pelting you with books or whacking you over the head with a fire extinguisher. That's hard. That requires more focus than the vast majority of civilians have. 

Besides - if there is no advantage to them, why do you want one? You know that argument doesn't hold water. If they didn't have a significant advantage in an offensive situation, you wouldn't see them issued to infantry around the world.

"If we give an inch, they will take a mile. They want to ban all guns!"

If we refuse to acknowledge that the gun is a force multiplier, and do not genuinely try to find a solution that reduces harm to society, we are far more likely to lose our gun rights. Casually replying that guns don't kill people in response to a tragedy where one mentally ill person has killed dozens of innocents is callous, and counterproductive. 

Decades ago, we as a nation decided that machine guns, suppressors, high explosives, and heavy weapons should be heavily controlled because they place unreasonable power to do harm in the hands of a single person. Our gun rights have not been eroded as a result. This should be extended to high capacity magazines to limit the harm a single ill person can do.

"The second amendment isn't about hunting. We must be ready to repel a foreign invader or a hostile government."

You can do that with a good scoped bolt action hunting rifle. You can do that with 10 round magazines. If you feel really, really strongly about it, obey the law, pass the background check, and buy yourself some high capacity magazines. Then lock them up.

"I need high capacity magazines to defend myself or my family."

High capacity magazines in a pistol are certainly potentially useful in an extended altercation on the street. If you really feel the need, it would still be available. It just would be a bit harder to do. It should be noted, though, that a review of the NRA's Armed Citizen covering 5 years of incidents involving the use of firearms by civilians for self defense indicated the following:

"As might be expected, the majority of incidents (52%) took place in the home. Next most common locale (32%) was in a business. Incidents took place in public places in 9% of reports and 7% occurred in or around vehicles.

The most common initial crimes were armed robbery (32%), home invasion (30%), and burglary (18%). Overall, shots were fired by the defender in 72% of incidents. The average and median number of shots fired was 2. When more than 2 shots were fired, it generally appeared that the defender’s initial response was to fire until empty." (emphasis mine)

Now, if you are talking about your AR, consider that carefully. If you live in a typical city or suburban area and are firing 30 rounds of .223 at your attacker, those rounds will go through walls and stand a high likelihood of injuring someone other than your attacker. 

"High capacity magazines are fun."

They sure are fun. But that is an absolutely inadequate reason to keep them so readily available when they make it easier for one mentally ill person to kill a couple dozen people. 

"The solution is to have more armed law abiding citizens."

That is an entirely separate potential solution that deserves careful study. It doesn't invalidate any of the arguments presented here.

Making high capacity magazines harder for an attacker to get will give victims under attack more time to flee, hide, or fight. 

We, as pro-gun people, need to acknowledge that the weapons we keep DO play a part in these tragedies. T-shirt slogans aren't good enough. We need to propose effective approaches to reducing the death toll from these terrible incidents.

Friday, November 3, 2017

Automated meteor/aircraft/satellite detection for sky camera in Python


In a previous post,  I described the construction of a simple networked sky camera built with a Raspberry Pi. I was pleased with how well it worked, but quickly figured out that manually reviewing the more than 5000 frames it generated per night was a drag. 

The following describes a Python script that makes uses calls to ImageMagick on a Linux computer to identify frames that potentially contain something interesting. In a typical night, it reduces the frames for manual review from 5000+ to a dozen or so, and it picks up lighter streaks than I tend to see rapidly skimming through by hand. There are certainly more sophisticated ways to do that, but I was surprised at how well this works. Specific drawbacks are mentioned below.

Things you are likely to catch with a sky camera

My sky camera exposes for 10 seconds per frame. As a result, a bright moving object will leave a line. You can interpret the line to determine what it is.

 1) Airplanes. Lots of airplanes. You'll be surprised at how many airplanes fly over your house or observatory.

Airplanes that fly at night are required to have strobe lights on the wing tips and vertical stabilizer. As a result, they produce a distictive dot-dash-dot-dash pattern as the fly across the sky during a long exposure, which is easy for a person to identify.

Also, they cross from one side of the frame to the other, and take several frames to do it - typically three to four. They don't appear in the middle of the sky and then disappear after short distances.


2) Satellites. Fewer than airplanes, and they are fairly easily distinguished. First, they don't have strobes, so they appear as a fairly consistent brightness that travels in a straight line. They also usually take 3-4 frames to cross from one side to the other. If it's a straight, non-strobing line that lasts more than two frames, it's not a meteor, since it is travelling too slowly across the sky.

A satellite - 1 frame of 3

3) Meteors. If it appears in no more than 2 frames (since it's possible for it to occur at the end of one frame and the start of another) and it doesn't cross the whole frame, congratulations - you've probably captured a rock from space! An airplane or satellite is not expected to start in the middle of the sky, but a meteor can.

Orionid meteor - Oct 2017. Stack of two sequential images that the meteor was on, cropped

Finding frames with possible objects in them

If you are running your sky camera on a clear night, detection of things moving can be as easy as identifying frames that are significantly different from the frame before it. Since the Earth is rotating, we expect it to change a little, so a "fuzz" factor is applied - a small amount of change is ignored. If that threshold is exceeded, though, we should set the frame aside for a person to look at. This simple operation sifts through thousands of frames and pulls out the ones that have something happening remarkably well. 

Of course, if you have trees or clouds in your frame, it's likely that motion of those will trigger it too - a false positive. Clouds can be identified reasonably well by simply dropping frames that exceed a certain brightness threshold, but that increases computing time and you might miss a frame that has something interesting in it that also has a cloud. It's a tradeoff. At the moment, I only capture images on pretty clear nights, so I leave the brightness thresholding turned off to speed processing. If you want the function enabled, you can just uncomment the line in main() that calls it.

Running the program

The program currently runs on a Linux computer with Python and ImageMagick installed. Most distros have these already. An example command looks like this. The first argument is the directory containing the images you captured, and the second is your desired output directory. Frames that the program determines may be interesting are copied to the output folder.

./ 20-10-2017 20-10-2017-output/

You must assign the program file execute privileges on your Linux box - usually, this will do the trick:

chmod u+x

Program listing and download

Listing follows... please let me know if you find it useful. 

#!/usr/bin/env python

import sys
import os
import subprocess
import shutil

def removeBrightImages(images, threshold):
 #The average graylevel of an image may be found using the string format "%[mean]"
 #convert image -format "%[mean]" info:
 count = 0
 darkFrames = []
 for image in images:
  if count > 0:

   command = 'convert ' + image + ' -format "%[mean]" info:'
    val = subprocess.check_output(command,shell=True) 

   except subprocess.CalledProcessError as e:

    val = e.output

   if float(val) < threshold:
    print "Adding " + image + ": brightness under threshold, queued for comparison"
    print "Rejecting " + image + ": brightness exceeds threshold"
  count = count + 1
 print darkFrames
 return darkFrames

def findChanges(images, fuzz, threshold):
 #fuzz is currently hardcoded below
 count = 0
 changedFrames = []
 commandList = []
 for image in images:
  if count > 0:
   #Trying to do this the better way with arguments and no shell=True results in the conversion
   #of the output to an int failing below, and I have not figured out why.

   #print "Comparing " + lastImage + " to " + image

   command = "compare -metric ae -fuzz 15% " +  lastImage + " " + image + " null: 2>&1"
    val = subprocess.check_output(command,shell=True) 

   #The compare program returns 2 on error otherwise 0 if the images are similar or 1 if they are dissimilar.
   except subprocess.CalledProcessError as e:

    val = e.output

        if e.returncode == 2:
     print "Error in image comparison routine."

   if int(val) > threshold:
    print image + ": " + val + ", item found"
    print "Checking: " + image 

  lastImage = image
  count = count + 1

 return changedFrames

def saveImages(images):
 for image in images:
  shutil.copy2(image, sys.argv[2]) 

def genImageList():
 imageList = []
 for file in os.listdir(sys.argv[1]):
      if file.endswith(".jpg"):
          imageList.append(os.path.join(sys.argv[1], file))
 return imageList

def checkArgs():
 if len(sys.argv) != 3:
  print "Usage: ./  "

 if os.path.isdir(sys.argv[2]):
  print "Output directory exists already, refusing to overwrite it. Exiting."
  print "Creating output directory"

def main():

 #if brightness thresholding is enabled, set threshold. Higher is brighter.
 brightnessThreshold = 2000

 #frame difference comparison senstivity. A higher value reduces sensitivity. 0-100.
 fuzzFactor = 15

 #the number of pixels that must be different between frames in order to flag it as interesting.
 diffThreshold = 100

 images = genImageList()
 #if you want to enable brightness thresholding, uncomment the line below
 #images = removeBrightImages(images, float(brightnessThreshold))
 changedFrames = findChanges(images, fuzzFactor, diffThreshold)

if __name__ == '__main__':