The pirates hijacked the Indian cargo ship last month, seizing the 10-man crew and holding them for ransom.
Security forces freed the vessel and two of the crew on Monday. The pirates escaped with the other eight who have now been freed, the official added.
The Al Kausar was the third ship hijacked within the space of a month after a five-year lull.
"The security forces overwhelmingly besieged them and the pirates tried to flee, but three of them were captured," Abdirashid Mohamed Ahmed, the deputy commander of the maritime force in Somalia's Galmudug state, told AFP news agency.
Mr Ahmed added that the newly freed crew members were "safe and healthy". He did not reveal the sailors' nationalities.
On Sunday sailors from the Indian, Pakistani and Chinese navies freed the crew of a Tuvalu-registered vessel which had been boarded by pirates.
Piracy in the waters off Somalia and Yemen peaked in 2011, with more than 200 attacks.
But it has dropped significantly in recent years, in part because of extensive international military patrols as well as support for local fishing communities.
However, the factors that drove many Somali coastal fishermen to become pirates nearly a decade ago are still there, says the BBC's security correspondent Frank Gardner.
Somalia is currently in the grip of a severe drought with hundreds of thousands facing hunger. Poverty is widespread with few employment options for young people.
There is also continued local resentment at illegal fishing off the Somali coast by Asian trawlers.
Somali security forces have rescued eight sailors who were kidnapped by pirates, an official says.