accessing each element in a numpy array - python

I'm attempting to remove stray white pixels from an alpha channel mask by looking at the adjacent pixels, but have been getting TypeEror: 'numpy.ndarray' object is not callable
I made an array using pygame.surfarray:
alphachannel3d = pygame.surfarray.pixels3d(alphachannel)
then attempt to step through it and change pixel values from white to black:
if (alphachannel3d[x] == (0, 0, 0)) & (alphachannel3d[x + 3] == (255, 255, 255)) & (alphachannel3d[x -3]==(255, 255, 255)):
alphachannel3d[x] = (255, 255, 255)
Here is the loop:
x=1
while 1:
count = x
print 'count is', count
print 'waiting 5 seconds'
pygame.time.wait(5000)
img = cam.get_image()
imgarray = pygame.PixelArray(img)
alphachannelarray = basearray.compare(imgarray, distance=0.09, weights=(0.01, 0.01, 0.01))
alphachannel = alphachannelarray.make_surface()
alphachannel3d = pygame.surfarray.pixels3d(alphachannel)
if (alphachannel3d[x] == (0, 0, 0)) & (alphachannel3d[x + 3] == (255, 255, 255)) & (alphachannel3d[x -3]==(255, 255, 255)):
alphachannel3d[x] = (255, 255, 255)
alphachannel = pygame.surfarray.make_surface(alphachannel3d)
srfcScreen.blit(alphachannel, (0,0))
print 'screen blitted'
pygame.display.flip()
print 'display flipped'
x = x+1

Based on your comment, I'm going to give the following speculative answer (without testing it):
if np.all(alphachannel3d[x] == (0, 0, 0)) & np.all(alphachannel3d[x + 3] == (255, 255, 255)) & np.all(alphachannel3d[x -3]==(255, 255, 255)):
alphachannel3d[x] = (255, 255, 255)

Related

OpenCV Code which I try cannot detect some ArUco's

As I learned from tutorial videos, I tried this code:
import numpy as np
import cv2
ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
}
#In fact there are more dictionary keys than written above. I deleted them to shorten the question.
def aruco_display(corners, ids, rejected, image):
if len(corners) > 0:
ids = ids.flatten()
for (markerCorner, markerID) in zip(corners, ids):
corners = markerCorner.reshape((4, 2))
(topLeft, topRight, bottomRight, bottomLeft) = corners
topRight = (int(topRight[0]), int(topRight[1]))
bottomRight = (int(bottomRight[0]), int(bottomRight[1]))
bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1]))
topLeft = (int(topLeft[0]), int(topLeft[1]))
cv2.line(image, topLeft, topRight, (0, 255, 0), 2)
cv2.line(image, topRight, bottomRight, (0, 255, 0), 2)
cv2.line(image, bottomRight, bottomLeft, (0, 255, 0), 2)
cv2.line(image, bottomLeft, topLeft, (0, 255, 0), 2)
cX = int((topLeft[0] + bottomRight[0]) / 2.0)
cY = int((topLeft[1] + bottomRight[1]) / 2.0)
cv2.circle(image, (cX, cY), 4, (0, 0, 255), -1)
cv2.putText(image, str(markerID),(topLeft[0], topLeft[1] - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0, 255, 0), 2)
print("[Inference] ArUco marker ID: {}".format(markerID))
return image
img = cv2.imread('markers.jpg', 1)
#the first parameter will change according to the name of the photo
aruco_type = ["DICT_4X4_50",
"DICT_4X4_100",
"DICT_4X4_250",
]
for i in aruco_type:
arucoDict = cv2.aruco.getPredefinedDictionary(ARUCO_DICT[i])
arucoParams = cv2.aruco.DetectorParameters()
corners, ids, rejected = cv2.aruco.ArucoDetector(arucoDict, arucoParams).detectMarkers(img)
detected_markers = aruco_display(corners, ids, rejected, img)
cv2.imshow("Image", detected_markers)
cv2.waitKey(0)
cv2.destroyAllWindows()
This code can detect most of codes but there is still problem due to not detecting some ArUco's like that:
ArUco1
ArUco2
How can I solve this issue?
I think if it can detect some of them, I don't understand why it cannot detect ArUco's on same image.

Circuitpython | Traceback ValueError | >BUTTON_A is being used<

Context
I hope I can get some help. Thanks in advance
I recently acquired a Circuit Playground Express as a project for college, and I am having some issues programming with it, specially because the Traceback is constantly giving me an error which I don't know how to fix, and I have tried several things now, and couldn't get anything different.
I am using a IDE for CircuitPython called "Mu Editor" https://codewith.mu/en/download, which provides me some interesting tools that have made my work kind of easier. (I have to clarify I have never coded in Python, so I am kinda lost in everything)
Error
Traceback (ultima llamada reciente):
Archivo "code.py", línea 61, en <module>
ValueError: BUTTON_A está siendo utilizado
El código terminó de ejecutar.
Code which is getting error
I am having the issue specially on these pieces of code:
Variable a_but, which will allow me to use the BUTTON_A of the Circuit Playground, so it does something when it is pressed
a_but = DigitalInOut(board.D4)
a_but.direction = Direction.INPUT
a_but.pull = Pull.DOWN
Variable b_but, which will allow me to use the BUTTON_B of the Circuit Playground, so it does something when it is pressed
b_but = DigitalInOut(board.D5)
b_but.direction = Direction.INPUT
b_but.pull = Pull.DOWN
Variable pixels that will allow me to access to modify the neopixels of the Circuit Playground
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1.0)
Examples of the above variables when being used:
a_but and b_but
while True:
if a_but.value:
print("Button A pressed")
if b_but.value:
print("Button B pressed")
pixels
if temp < 36:
pixels[0] = (0, 0, 255)
pixels[1] = (0, 0, 255)
pixels[2] = (0, 0, 255)
elif temp >= 36 and temp <= 37.2:
pixels[3] = (0, 0, 255)
pixels[4] = (0, 0, 255)
pixels[5] = (0, 0, 255)
pixels[6] = (0, 0, 255)
else:
pixels[7] = (0, 0, 255)
pixels[8] = (0, 0, 255)
pixels[9] = (0, 0, 255)
Here is the complete code in case you want to take a look (It might have some errors since that error is blocking me from moving on):
import time
import analogio
import board
import neopixel
import pulseio
import digitalio
from digitalio import DigitalInOut, Direction, Pull
import adafruit_irremote
import adafruit_thermistor
from adafruit_circuitplayground import cp
def sign(value):
if value > 0:
return 1
if value < 0:
return -1
return 0
def pulse_test():
# Turn only pixel #1 green
pixels[1] = (0, 255, 0)
# How many light readings per sample
NUM_OVERSAMPLE = 10
# How many samples we take to calculate 'average'
NUM_SAMPLES = 20
samples = [0] * NUM_SAMPLES
i = True
while i:
for i in range(NUM_SAMPLES):
# Take NUM_OVERSAMPLE number of readings really fast
oversample = 0
for s in range(NUM_OVERSAMPLE):
oversample += float(light.value)
# and save the aver age from the oversamples
samples[i] = oversample / NUM_OVERSAMPLE # Find the average
mean = sum(samples) / float(len(samples)) # take the average
print((samples[i] - mean,)) # 'center' the reading
if i > 0:
# If the sign of the data has changed munus to plus
# we have one full waveform (2 zero crossings), pulse LED
if sign(samples[i] - mean) <= 0 and sign(samples[i - 1] - mean) > 0:
pixels[9] = (200, 0, 0) # Pulse LED
else:
pixels[9] = (0, 0, 0) # Turn LED off
time.sleep(0.025) # change to go faster/slower
if b_but.value:
i = False
pixels[1] = (0, 0, 0)
pixels[9] = (0, 0, 0)
a_but = DigitalInOut(board.D4)
a_but.direction = Direction.INPUT
a_but.pull = Pull.DOWN
b_but = DigitalInOut(board.D5)
b_but.direction = Direction.INPUT
b_but.pull = Pull.DOWN
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1.0)
light = analogio.AnalogIn(board.LIGHT)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
PIXELS_OFF = (0, 0, 0)
pulsein = pulseio.PulseIn(board.IR_RX, maxlen=120, idle_state=True)
decoder = adafruit_irremote.GenericDecode()
while True:
pulse = decoder.read_pulses(pulsein)
try:
received_code = decoder.decode_bits(pulse)
print("\n\nSeñal Adquirida : ", received_code)
if received_code == (223, 32, 111, 144):
print("¡Sospecha de infeccion detectada!\n\n")
for i in range(3):
pixels.fill(YELLOW)
pixels.show()
time.sleep(0.05)
pixels.fill(PIXELS_OFF)
pixels.show()
time.sleep(0.05)
print("¿Desea realizar un testeo basico?:")
print("\n\n Si. Presione A\n No. Presione B")
pixels[0] = (0, 255, 0)
pixels[1] = (0, 255, 0)
pixels[2] = (0, 255, 0)
pixels[3] = (0, 255, 0)
pixels[4] = (0, 255, 0)
pixels[5] = (255, 0, 0)
pixels[6] = (255, 0, 0)
pixels[7] = (255, 0, 0)
pixels[8] = (255, 0, 0)
pixels[9] = (255, 0, 0)
while True:
if a_but.value:
testeo_respuesta = True
for x in range(2):
pixels.fill(PIXELS_OFF)
pixels.show()
for i in range(9):
pixels[10] = (0, 255, 0)
time.sleep(0.075)
break
if b_but.value:
testeo_respuesta = False
for x in range(2):
pixels.fill(PIXELS_OFF)
pixels.show()
for i in range(9):
pixels[i] = (255, 0, 0)
time.sleep(0.075)
break
time.sleep(0.075)
pixels.fill(PIXELS_OFF)
pixels.show()
if testeo_respuesta:
for test_num in range(19):
regTemp = [cp.temperature] * test_num
time.sleep(1.0)
for k in range(19):
pixels[0] = (0, 0, 255)
temp = 0
if temp < regTemp[k]:
temp = regTemp[k]
pixels[0] = (0, 0, 0)
time.sleep(0.5)
if temp < 36:
pixels[0] = (0, 0, 255)
pixels[1] = (0, 0, 255)
pixels[2] = (0, 0, 255)
pixels[3] = (0, 0, 0)
pixels[4] = (0, 0, 0)
pixels[5] = (0, 0, 0)
pixels[6] = (0, 0, 0)
pixels[7] = (0, 0, 0)
pixels[8] = (0, 0, 0)
pixels[9] = (0, 0, 0)
resultado = True
elif temp >= 36 and temp <= 37.2:
pixels[0] = (0, 0, 0)
pixels[1] = (0, 0, 0)
pixels[2] = (0, 0, 0)
pixels[3] = (0, 0, 255)
pixels[4] = (0, 0, 255)
pixels[5] = (0, 0, 255)
pixels[6] = (0, 0, 255)
pixels[7] = (0, 0, 0)
pixels[8] = (0, 0, 0)
pixels[9] = (0, 0, 0)
resultado = False
else:
pixels[0] = (0, 0, 0)
pixels[1] = (0, 0, 0)
pixels[2] = (0, 0, 0)
pixels[3] = (0, 0, 0)
pixels[4] = (0, 0, 0)
pixels[5] = (0, 0, 0)
pixels[6] = (0, 0, 0)
pixels[7] = (0, 0, 255)
pixels[8] = (0, 0, 255)
pixels[9] = (0, 0, 255)
resultado = True
else:
print("¡No hay riesgo detectado!")
for i in range(3):
pixels.fill(GREEN)
pixels.show()
time.sleep(0.05)
pixels.fill(PIXELS_OFF)
pixels.show()
time.sleep(0.05)
except:
continue
time.sleep(0.025)

Object Detection Using Raspberry Pi and Android IP Camera with Python and OpenCV

Here is my code that I have used for object detection using raspberry pi and Android Ip Camera. Here I'm not getting any output and the code does not provide any errors. Can someone figure out what is the error?
import urllib.request
import cv2
import numpy as np
import datetime
import math
#global variables
width = 0
height = 0
EntranceCounter = 0
ExitCounter = 0
MinCountourArea = 3000 #Adjust ths value according to your usage
BinarizationThreshold = 70 #Adjust ths value according to your usage
OffsetRefLines = 150 #Adjust ths value according to your usage
#Check if an object in entering in monitored zone
def CheckEntranceLineCrossing(y, CoorYEntranceLine, CoorYExitLine):
AbsDistance = abs(y - CoorYEntranceLine)
if ((AbsDistance <= 2) and (y < CoorYExitLine)):
return 1
else:
return 0
#Check if an object in exitting from monitored zone
def CheckExitLineCrossing(y, CoorYEntranceLine, CoorYExitLine):
AbsDistance = abs(y - CoorYExitLine)
if ((AbsDistance <= 2) and (y > CoorYEntranceLine)):
return 1
else:
return 0
This is the code i have used to obtain the video stream from my IP camera
ReferenceFrame = None
while True:
camera=cv2.VideoCapture("http://192.168.1.6:8080/shot.jpg")
camera.set(3,640)
camera.set(4,480)
(ret,Frame)=camera.read()
height = np.size(Frame,0)
width = np.size(Frame,1)
#if cannot grab a frame, this program ends here.
if not ret:
break
This is the code part i have used to display the lines and frame for object detection and object counting
#gray-scale convertion and Gaussian blur filter applying
GrayFrame = cv2.cvtColor(Frame, cv2.COLOR_BGR2GRAY)
GrayFrame = cv2.GaussianBlur(GrayFrame, (21, 21), 0)
if ReferenceFrame is None:
ReferenceFrame = GrayFrame
continue
#Background subtraction and image binarization
FrameDelta = cv2.absdiff(ReferenceFrame, GrayFrame)
FrameThresh = cv2.threshold(FrameDelta, BinarizationThreshold, 255, cv2.THRESH_BINARY)[1]
#Dilate image and find all the contours
FrameThresh = cv2.dilate(FrameThresh, None, iterations=2)
_, cnts, _ = cv2.findContours(FrameThresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
QttyOfContours = 0
#plot reference lines (entrance and exit lines)
CoorYEntranceLine = (height / 2)-OffsetRefLines
CoorYExitLine = (height / 2)+OffsetRefLines
cv2.line(Frame, (0,CoorYEntranceLine), (width,CoorYEntranceLine), (255, 0, 0), 2)
cv2.line(Frame, (0,CoorYExitLine), (width,CoorYExitLine), (0, 0, 255), 2)
#check all found countours
for c in cnts:
#if a contour has small area, it'll be ignored
if cv2.contourArea(c) < MinCountourArea:
continue
QttyOfContours = QttyOfContours+1
#draw an rectangle "around" the object
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(Frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
#find object's centroid
CoordXCentroid = (x+x+w)/2
CoordYCentroid = (y+y+h)/2
ObjectCentroid = (CoordXCentroid,CoordYCentroid)
cv2.circle(Frame, ObjectCentroid, 1, (0, 0, 0), 5)
if (CheckEntranceLineCrossing(CoordYCentroid,CoorYEntranceLine,CoorYExitLine)):
EntranceCounter += 1
if (CheckExitLineCrossing(CoordYCentroid,CoorYEntranceLine,CoorYExitLine)):
ExitCounter += 1
print ("Total countours found: "+str(QttyOfContours))
#Write entrance and exit counter values on frame and shows it
cv2.putText(Frame, "Entrances: {}".format(str(EntranceCounter)), (10, 50),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (250, 0, 1), 2)
cv2.putText(Frame, "Exits: {}".format(str(ExitCounter)), (10, 70),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.imshow('Salida',Frame)
cv2.waitKey(1);
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
The correct code
import numpy as np
import math
def nothing(x):
pass
width=0
height=0
EntranceCounter = 0
OffsetRefLines = 150
ExitCounter = 0
BinarizationThreshold = 70
MinCountourArea = 3000
cap = cv2.VideoCapture(0);
path="http://192.168.1.6:8080/video"
cap.open(path)
ReferenceFrame = None
#Check if an object in entering in monitored zone
def CheckEntranceLineCrossing(y, CoorYEntranceLine, CoorYExitLine):
AbsDistance = abs(y - CoorYEntranceLine)
if ((AbsDistance <= 2) and (y < CoorYExitLine)):
return 1
else:
return 0
#Check if an object in exitting from monitored zone
def CheckExitLineCrossing(y, CoorYEntranceLine, CoorYExitLine):
AbsDistance = abs(y - CoorYExitLine)
if ((AbsDistance <= 2) and (y > CoorYEntranceLine)):
return 1
else:
return 0
#cv2.namedWindow("Tracking")
cv2.createTrackbar("LH", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LS", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LV", "Tracking", 0, 255, nothing)
cv2.createTrackbar("UH", "Tracking", 255, 255, nothing)
cv2.createTrackbar("US", "Tracking", 255, 255, nothing)
cv2.createTrackbar("UV", "Tracking", 255, 255, nothing)
while True:
#frame = cv2.imread('smarties.png')
if cap.isOpened():
rval, frame = cap.read()
while rval:
rval,frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
hsv = cv2.GaussianBlur(hsv, (21, 21), 0)
if ReferenceFrame is None:
ReferenceFrame = hsv
continue
#Background subtraction and image binarization
FrameDelta = cv2.absdiff(ReferenceFrame, hsv)
FrameThresh = cv2.threshold(FrameDelta, 25, 255, cv2.THRESH_BINARY)[1]
#Dilate image and find all the contours
FrameThresh = cv2.dilate(FrameThresh, None, iterations=2)
cnts, _ = cv2.findContours(FrameThresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
QttyOfContours = 0
#plot reference lines (entrance and exit lines)
cv2.line(frame, (0,170), (2000,170), (255, 0, 0), 5)
cv2.line(frame, (0,470), (2000,470), (0, 0, 255), 5)
#check all found countours
for c in cnts:
#if a contour has small area, it'll be ignored
if cv2.contourArea(c) < MinCountourArea:
continue
QttyOfContours = QttyOfContours+1
#draw an rectangle "around" the object
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
#find object's centroid
CoordXCentroid = int(x+x+w)/2
CoordYCentroid = int(y+y+h)/2
ObjectCentroid = (x,y)
cv2.circle(frame, ObjectCentroid, 2, (0, 255, 0), 5)
if (CheckEntranceLineCrossing(CoordYCentroid,170,470)):
EntranceCounter += 1
if (CheckExitLineCrossing(CoordYCentroid,170,470)):
ExitCounter += 1
print ("Total countours found: "+str(QttyOfContours))
#Write entrance and exit counter values on frame and shows it
cv2.putText(frame, "Entrances: {}".format(str(EntranceCounter)), (10, 50),
cv2.FONT_HERSHEY_SIMPLEX, 2, (250, 0, 1), 2)
cv2.putText(frame, "Exits: {}".format(str(ExitCounter)), (10, 110),
cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2)
imS = cv2.resize(frame, (400, 400)) # Resize image
#imSS = cv2.resize(mask, (200, 200))
#imSSS = cv2.resize(frame, (200, 200))
cv2.imshow("frame", imS)
#cv2.imshow("mask", imSS)
#cv2.imshow("res", imSSS)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()

Is it possible to call object from another object

I am trying to make a class for colors in pygame.
This is what I have now.
class color:
white = (255, 255, 255)
black = (0, 0, 0)
red = (200, 0 ,0)
green = (0, 200, 0)
blue = (0, 0, 200)
brightRed = (255, 0, 0)
darkRed = (127, 0, 0)
color = color()
print (color.brightRed)
And this as expected will print (255, 0, 0).
I wonder is it possible to make something like this:
color = color()
print(color.red)
print(color.red.bright)
print(color.red.dark)
So I can get the next prints:
(200, 0 ,0)
(255, 0, 0)
(127, 0, 0)
I know that this example is pointless, but I could make something else if it is possible.
You can define another class
class Red:
bright = (255, 0, 0)
dark = (127, 0, 0)
normal = (200, 0, 0)
class color:
white = (255, 255, 255)
black = (0, 0, 0)
red = Red
green = (0, 200, 0)
blue = (0, 0, 200)
brightRed = Red.bright
darkRed = Red.dark
color = color()
print(color.red.normal)
print(color.red.bright)
print(color.red.dark)
You can't have color.red be both a user-defined class and a tuple at the same time, so you can't use color.red in place of color.red.normal. But you could have normalRed = Red.normal and then use color.normalRed.

How to break your code up into smaller chunks, turn those chunks of code into functions, and then call the functions from within main in python?

I need a way to break my code up into smaller chunks, turn those chunks of code into functions, and then call the functions from within main.
import picture
def main():
# Size of the canvas
canvaswidth = 500
canvasheight = 500
canvas = picture.Picture(canvaswidth, canvasheight)
# My color pallette
black = (0, 0, 0)
purple = (128, 0, 128)
cream = (255, 255, 240)
brown = (102,51, 0)
blue = (0, 76, 173)
red = (255, 0, 0)
yellow = (255, 255, 0)
canvas.setFillColor(brown)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawRectFill(175,75,100,300)
canvas.setFillColor(red)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawPolygonFill([175,75,225,25,275,75])
canvas.setFillColor(red)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawPolygonFill([175,430,200,300,250,300,275,430])
canvas.setFillColor(red)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawPolygonFill([125,400,150,300,175,300,175,375])
canvas.setFillColor(red)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawPolygonFill([275,375,275,300,300,300,325,400])
canvas.display()
main()
Without knowing more about your purpose and motivation, it's difficult to give you an answer. Did you mean something like the following?
# Size of the canvas
canvaswidth = 500
canvasheight = 500
canvas = picture.Picture(canvaswidth, canvasheight)
# My color pallette
black = (0, 0, 0)
purple = (128, 0, 128)
cream = (255, 255, 240)
brown = (102,51, 0)
blue = (0, 76, 173)
red = (255, 0, 0)
yellow = (255, 255, 0)
def doit(canvas, fill_color, draw_method, *data):
canvas.setFillColor(fill_color)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
getattr(canvas, draw_method)(*data)
def main():
canvas = picture.Picture(canvaswidth, canvasheight)
doit(canvas, brown, 'drawRectFill', 175,75,100,300)
doit(canvas, red, 'drawPolygonFill', [175,75,225,25,275,75])
doit(canvas, red, 'drawPolygonFill', [175,430,200,300,250,300,275,430])
doit(canvas, red, 'drawPolygonFill', [125,400,150,300,175,300,175,375])
doit(canvas, red, 'drawPolygonFill', [275,375,275,300,300,300,325,400])
canvas.display()

Categories