Cv2 findChessboardCorners fails to find corners on the images - cv2

I am trying to calibrate the camera with 10-50mm focal lenght, all the images of the chess board are taken with cube size as 0.25cm. when i run the findchessboard function of cv2, it fails to detect the chessboard.
image
file = "filename"
img = cv2.imread(file)
# Color-segmentation to get binary mask
lwr = np.array([0, 0, 90])
upr = np.array([179, 61, 252])
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
msk = cv2.inRange(hsv, lwr, upr)
plt.imshow(msk)
plt.show()
# Extract chess-board
krn = cv2.getStructuringElement(cv2.MORPH_RECT, (50, 30))
dlt = cv2.dilate(msk, krn, iterations=5)
res = 255 - cv2.bitwise_and(dlt, msk)
# Displaying chess-board features
res = np.uint8(res)
plt.imshow(res)
plt.show()
ret, corners = cv2.findChessboardCorners(gray, (9, 7),
flags=cv2.CALIB_CB_ADAPTIVE_THRESH +
cv2.CALIB_CB_FAST_CHECK +
cv2.CALIB_CB_NORMALIZE_IMAGE +
cv2.CALIB_CB_EXHAUSTIVE)
if ret:
print(corners)
fnl = cv2.drawChessboardCorners(img, (7, 7), corners, ret)
plt.imshow(fnl)
plt.show
else:
print("No Checkerboard Found")

Related

Error: x,y coords given but no window specified (spatstat)

I am generating a landscape pattern that evolves over time. The problem with the code is that I have clearly defined a window for the object bringing up the error but the window is not being recognised. I also do not see how any points are falling outside of the window, or how that would make a difference.
library(spatstat)
library(dplyr)
# Define the window
win <- owin(c(0, 100), c(0, 100))
# Define the point cluster
cluster1 <- rMatClust(kappa = 0.0005, scale = 0.1, mu = 20,
win = win, center = c(5,5))
# define the spread of the points
spread_rate <- 1
new_nests_per_year<-5
years<-10
# Plot the initial cluster
plot(win, main = "Initial cluster")
points(cluster1, pch = 20, col = "red")
newpoints<-list()
# Loop for n years
for (i in 1:years) {
# Generate new points that spread from the cluster
newpoints[[1]] <-rnorm(new_nests_per_year, mean = centroid.owin(cluster1)$y, sd = spread_rate)
newpoints[[2]] <-rnorm(new_nests_per_year, mean = centroid.owin(cluster1)$x, sd = spread_rate)
# Convert the list to a data frame
newpoints_df <- data.frame(newpoints)
# Rename the columns of the data frame
colnames(newpoints_df) <- c("x", "y")
# Combine the new points with the existing points
cluster1_df <- data.frame(cluster1)
newtotaldf<-bind_rows(cluster1_df,newpoints_df)
cluster1<-as.ppp(newtotaldf, x = newtotaldf$x, y = newtotaldf$y,
window = win)
# Plot the updated cluster
plot(win, main = paste("Cluster after year", i))
points(cluster1, pch = 20, col = "red")
}
However, when I run line:
cluster1<-as.ppp(newtotaldf, x = newtotaldf$x, y = newtotaldf$y,
window = win)
I recieve the error:
Error: x,y coords given but no window specified
Why would this be the case?
In your code, if you use the command W = win it should solve the issue. I also believe you can simplify the command without specifying x and y:
## ...[previous code]...
cluster1 <- as.ppp(newtotaldf, W = win)
plot(win)
points(cluster1, pch = 20, col = "red")

How to move object across axis?

I have an interactive plot and I want to move topoplot position across the x-axis according to the slider (or red vertical bar) position.
How can I do that?
In an ideal situation, the topoplot moves until some border (so it would be partially out of the screen).
Also, is it possible to put a line connecting the topolot with a red vertical line?
This is my script with prerequisite functions:
using Makie
using GLMakie
using PyMNE
using JLD2 # loading data
using TopoPlots
using StatsBase # mean/std
using Pipe
using ColorSchemes
using Colors
using LinearAlgebra
function eegHeadMatrix(positions, center, radius)
oldCenter = mean(positions)
oldRadius, _ = findmax(x-> LinearAlgebra.norm(x .- oldCenter),
positions)
radF = radius/oldRadius
return Makie.Mat4f(radF, 0, 0, 0,
0, radF, 0, 0,
0, 0, 1, 0,
center[1]-oldCenter[1]*radF, center[2]-
oldCenter[2]*radF, 0, 1)
end
struct NullInterpolator <: TopoPlots.Interpolator
end
function (ni::NullInterpolator)(
xrange::LinRange, yrange::LinRange,
positions::AbstractVector{<: Point{2}}, data::AbstractVector{<:Number})
return zeros(length(xrange),length(yrange))
end
function posToColor(pos)
cx = 0.5 - pos[1]
cy = 0.5 - pos[2]
rx = cx * 0.7071068 + cy * 0.7071068
ry = cx * -0.7071068 + cy * 0.7071068
b = 1.0 - (2*sqrt(cx^2+cy^2))^2
return RGB(0.5 - rx*1.414, 0.5 - ry*1.414, b)
end
This is the main function
f = Figure(backgroundcolor = RGBf(0.98, 0.98, 0.98), resolution = (1500, 700))
# interaction
xs = range(-0.3, length=size(dat_e, 2), step=1 ./ 128)
sg = SliderGrid(f[4, 1:2],
(label="time", range=xs, format = "{:.3f} ms", startvalue = 0),
)
time = sg.sliders[1].value
str = lift(t -> "[$(round(t, digits = 3)) ms]", time)
topo_slice = lift((t, data) -> mean(data[1:30, indexin(t, xs), :], dims=2)[:,1], time, dat_e)
# butterfly plot
ax = Axis(f[2:3, 1:2], xlabel = "Time [s]", ylabel = "Voltage amplitude [µV]")
N = 1:length(pos) #1:4
hidespines!(ax, :t, :r)
GLMakie.xlims!(-0.3, 1.2)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
times = range(-0.3, length=size(dat_e,2), step=1 ./ 128)
specialColors = ColorScheme(vcat(RGB(1,1,1.),[posToColor(pos) for pos in pos[N]]...))
for i in N
mean_trial = mean(dat_e[i,:,:], dims=2)[:,1]
lines!(times, mean_trial, color = specialColors[i])
end
hidedecorations!(ax, label = false, ticks = false, ticklabels = false)
# text
vlines!(time, color = :red, linewidth = 1)
text!(time, 8, text = str, align = (:center, :center))
# topoplot
topo_axis = Axis(f[1, 1:2], width = 178, height = 178, aspect = DataAspect())
Makie.xlims!(low = -0.2, high = 1.2)
Makie.ylims!(low = -0.2, high = 1.2)
topoMatrix = eegHeadMatrix(pos[N], (0.5, 0.5), 0.5)
topo = eeg_topoplot!(topo_axis, topo_slice, # averaging all trial of 30 participants on Xth msec
raw.ch_names[1:30];
positions=pos, # produced automatically from ch_names
#interpolation=DelaunayMesh(),
enlarge=1,
extrapolation=GeomExtrapolation(enlarge=1.0, geometry=Circle),
label_text=false)
hidedecorations!(current_axis())
hidespines!(current_axis())
f

How to interact with plot using keyboard arros?

My interactive plot (topoplot) reacts to mouse signals, but how to make it reacting to keyboard signals?
Here is my code:
f = Figure()
xs = 1:1:193 #range(-30, 120, length = size(dat_e, 2))
sg = SliderGrid(f[2, 1],
(label="time", range=xs, format = "{:d} ms", startvalue = 100),
)
time = sg.sliders[1].value
str = lift(t -> "[$t ms]", time)
topo_slice = lift((t, data) -> mean(data[1:30, t, :], dims=2)[:,1], time, dat_e)
topo_axis = Axis(f[1, 1], aspect = DataAspect())
topo = eeg_topoplot!(topo_axis, topo_slice,
raw.ch_names[1:30];
positions=pos, # produced automatically from ch_names
label_text=true) # aspect ratio, correlation of height and width
text!(topo_axis, 1, 1, text = str, align = (:center, :center))
#topo_slice = lift((t, data) -> data[:, :, t], time, topo)
xlims!(-0.2, 1.1)
ylims!(-0.2, 1.2)
hidedecorations!(topo_axis)
hidespines!(topo_axis)
f
There is an official instruction https://docs.juliahub.com/AbstractPlotting/6fydZ/0.12.11/interaction.html, but as usual with Julia documentations, there is no example and I have no idea how implement it in my code.
How my plot looks like:
Expanding on the answer from before:
T = 10
pts = range(-1, 1, length=100)
ts = reshape(1:T, 1, 1, :)
topo = cos.(pts) .+ cos.(ts .* pts')
fig = Figure()
ax = Axis(fig[1, 1])
sg = SliderGrid(fig[2,1],
(label="time", range=1:T))
time = sg.sliders[1].value
str = lift(t -> "[$t ms]", time)
text!(ax, str)
topo_slice = lift((t, data) -> data[:, :, t], time, topo)
# decrement/increment slider with left/right keys
on(events(fig).keyboardbutton) do btn
if btn.action in (Keyboard.press, Keyboard.repeat)
if btn.key == Keyboard.left
set_close_to!(sg.sliders[1], time[] - 1)
elseif btn.key == Keyboard.right
set_close_to!(sg.sliders[1], time[] + 1)
end
end
end
contour!(ax, topo_slice)
hidedecorations!(ax)
hidespines!(ax)
fig

<SOLVED> How to plot a sphere as wireframe with back view hidden, in R?

Using R, I would like to plot a sphere with latitude and longitude lines, but without any visibility of hidden part of the sphere. And, ideally, I'd like to have the initial view start out with a specific tilt (but that's down the road).
This matlab question gets to the idea
Plotting a wireframe sphere in Python hidding backward meridians and parallels
... but it's matlab. The closest solution that stackoverflow suggested
Plot Sphere with custom gridlines in R
doesn't help with the hidden line aspect.
The closest I got was editting a sphereplot routine:
library(sphereplot)
matt.rgl.sphgrid <- function (radius = 1, col.long = "red", col.lat = "blue", deggap = 15,
longtype = "H", add = FALSE, radaxis = TRUE, radlab = "Radius")
{
if (add == F) {
open3d(userMatrix = rotationMatrix((90)*pi/180, 1, 0, 0)) #changed
}
for (lat in seq(-90, 90, by = deggap)) {
if (lat == 0) {
col.grid = "grey50"
}
else {
col.grid = "grey"
}
#create an array here using the sph2car call below, then rotate those and
#set the appropriate ones to NA before passing that array to this call
#ditto for the next plot3d call as well
plot3d(sph2car(long = seq(0, 360, len = 100), lat = lat,
radius = radius, deg = T),
col = col.grid, add = T,
type = "l")
}
for (long in seq(0, 360 - deggap, by = deggap)) {
if (long == 0) {
col.grid = "grey50"
}
else {
col.grid = "grey"
}
plot3d(sph2car(long = long, lat = seq(-90, 90, len = 100),
radius = radius, deg = T),
col = col.grid, add = T,
type = "l")
}
if (longtype == "H") {
scale = 15
}
if (longtype == "D") {
scale = 1
}
# rgl.sphtext(long = 0, lat = seq(-90, 90, by = deggap), radius = radius,
# text = seq(-90, 90, by = deggap), deg = TRUE, col = col.lat)
# rgl.sphtext(long = seq(0, 360 - deggap, by = deggap), lat = 0,
# radius = radius, text = seq(0, 360 - deggap, by = deggap)/scale,
# deg = TRUE, col = col.long)
}
matt.rgl.sphgrid(radaxis=FALSE)
But I can't figure out how to hide the lines.
Any pointers or examples I've overlooked?
SOLUTION: Just prior to the plot3d calls, set any negative values in "y" (in this case, given a first rotation of 90 degrees) to NA

Trapezoid Integration in Scilab - Polygon Color Fill Stops

I have been working on a program in Scilab that numerically integrates a function by the trapezoidal rule (without using the built-in function). I have no problem with the integration or plotting the function, but I want to overlay the real function on a plot of the trapezoids, colored in.
For some reason, when I set the bounds a = 0 to b = 3, no problem, I get exactly what I want. However, when I set the bounds above 3, the trapezoids will still plot (by lines), but they won't be colored in. In the code below, the color stops at 3. If I plot 0 to 6, for example, the color stops half-way through. 3 to 6, and there is no color at all.
Here are the relevant sections of code:
deff('[y] = f(x)','y = e^(x^2)'); // Definition of function
a = 0; // Lower bound
b = 4; // Upper bound
n = 20; // Number of intervals
h = ((b - a)/n); // Interval spacing
x = a:h:b; // Array of positions for division
and
for i = 1:n+1
y(i) = f(x(i));
end
and
for i = 1:n // Plot colored trapezoids
x_start = a+(h*(i-1));
x_end = a+(h*(i));
y_start = y(i);
y_end = y(i+1);
xpts = [x_start, x_end, x_end, x_start];
ypts = [y_start, y_end, 0, 0];
xfpoly(xpts,ypts,3);
end
This is the plot output for a = 0, b = 3
What version of Scilab are you using?
I tried your code with Scilab 5.4.1 (64bit) and I got uncolored trapezoids, but with 5.5.2 (64bit) all the shapes are nice green.
So maybe there was some bugfix between these versions.
I also changed your function definition from 'y = e^(x^2)' to 'y = %e^(x^2)' since the Euler number is a predefined variable (at least in 5.5.2).
clc;
clear;
deff('[y] = f(x)','y = %e^(x^2)'); // Definition of function
a = 0; // Lower bound
b = 6; // Upper bound
n = 100; // Number of intervals
h = ((b - a)/n); // Interval spacing
x = a:h:b; // Array of positions for division
for i = 1:n+1
y(i) = f(x(i));
end
scf(0);
clf(0);
plot2d(x,y);
for i = 1:n // Plot colored trapezoids
x_start = a+(h*(i-1));
x_end = a+(h*(i));
y_start = y(i);
y_end = y(i+1);
xpts = [x_start, x_end, x_end, x_start];
ypts = [y_start, y_end, 0, 0];
xfpoly(xpts,ypts,3);
end

Resources